LiveData
https://developer.android.google.cn/topic/libraries/architecture/livedata
LiveData和ViewModel的关系
在ViewModel中的数据发生变化时通知页面
public class MyviewModel extends viewModel {
//MutableLiveData是LiveData子类
private MutableLiveData<Integer> currentsecond;
//private MutableLiveData<Integer> currentsecond = new MutableLiveData<>(0);
public MutableLiveData<Integer> getCurrentSecond () {
if(currentSecond == null) {
currentsecond = new MutableLiveData<>();
currentsecond.setvalue (0) ;
}
return currentSecond;
}
}
//非UI线程使用postVaule(),UI线程使用setvalue()
viewModel.getCurrentSecond().postValue
//监听LiveData数据变化
viewModel.getCurrentSecond().observe(this,new Observerr<Interger>(){
@override
public void onChanged(Interger i){
textview.setText(String.valueOf(i));
}
});
LiveData的优势
确保界面符合数据状态
不会发生内存泄漏
不会因Activity停止而导致崩溃
不再需要手动处理生命周期
数据始终保持最新状态
适当的配置更改
共享资源