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:测试数据二
来源:CSDN
作者:蓝枫amy
链接:https://blog.csdn.net/u014005316/article/details/103973430