LiveData

99封情书 提交于 2020-01-14 17:54:41

LiveData是什么?

具有生命周期感知的、可观察的数据持有者

 

基本使用

 MutableLiveData<String> mutableLiveData = new MutableLiveData<>();
        mutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String s) {
                Log.e("zhoujian", "onChanged:" + s);
            }
        });

        //setValue: 在主线程调用
        //postValue: 可以在子线程中调用
        mutableLiveData.postValue("测试数据");
01-14 15:01:13.562 24808-24808/com.zhoujian.lifecycledemo E/zhoujian: onChanged:测试数据

 

map

 MutableLiveData<String> mutableLiveData = new MutableLiveData<>();
        mutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String s) {
                Log.e("zhoujian", "onChanged:" + s);
            }
        });

        LiveData transformations = Transformations.map(mutableLiveData, new Function<String, Object>() {
            @Override
            public Object apply(String input) {
                return "测试数据二";
            }
        });

        transformations.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Log.e("zhoujian", "onChanged:" + o.toString());
            }
        });
        mutableLiveData.postValue("测试数据一");
01-14 15:03:12.308 25407-25407/com.zhoujian.lifecycledemo E/zhoujian: onChanged:测试数据一
01-14 15:03:12.308 25407-25407/com.zhoujian.lifecycledemo E/zhoujian: onChanged:测试数据二

 

switchmap

final MutableLiveData<String> mutableLiveData1 = new MutableLiveData<>();
        final MutableLiveData<String> mutableLiveData2 = new MutableLiveData<>();
        MutableLiveData<Boolean> mutableLiveData3 = new MutableLiveData<>();
        LiveData transformations = Transformations.switchMap(mutableLiveData3, new Function<Boolean, LiveData<String>>() {
            @Override
            public LiveData<String> apply(Boolean b) {
                if (b) {
                    return mutableLiveData1;
                } else {
                    return mutableLiveData2;
                }

            }
        });

        transformations.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.e("zhoujian", "onChanged:" + s.toString());
            }
        });
        mutableLiveData3.postValue(false);
        mutableLiveData1.postValue("测试数据一");
        mutableLiveData2.postValue("测试数据二");

 

01-14 15:06:59.101 25989-25989/com.zhoujian.lifecycledemo E/zhoujian: onChanged:测试数据二

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!