观察者模式LiveData使用;
为了降低代码耦合度而优化的类,方便后期维护;开闭原则;
这个类只要拿到ViewModelProviders.of(this).get(WelcomeLiveDate.class);就能在其他类中更新数据.
ViewModel是后台数据类,不会被Activity影响,数据储存比较安全,而且方便维护;
LiveData是配合ViewModel使用而产生的类,主要用于数据更新时,在任何地方的代码都可以更新界面.
以上是个人见解,不对请留言指正;
复杂的活简单解说,以下结合官方做出5个小步骤:
转载注明出处:by xyx IN csdn@包罗万码
地址:https://blog.csdn.net/a316375/article/details/83041101
创建一个后台数据类;
public class WelcomeLiveDate extends ViewModel {
MutableLiveData<String> strings;
public MutableLiveData<String> getCurrentName() {
if (strings == null) strings = new MutableLiveData<String>();
return strings;
}
}
使用的时候:
public class WelcomeActivity extends AppCompatActivity {
.......
@Override
protected void onCreate(Bundle savedInstanceState) {
.......
//1.实例化数据类LiveDate
welLiveDate = ViewModelProviders.of(this).get(WelcomeLiveDate.class);
//2.创建一个观察类
Observer<String> nameObserver=new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
view.setText(s);//4.观察类观察到数据更新时候,通知UI更新界面
}
};
//3.绑定观察类
welLiveDate.getCurrentName().observe(this,nameObserver);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//5.数据变化时候推送给观察者
welLiveDate.getCurrentName().setValue("123");//主线程
welLiveDate.getCurrentName().postValue("456");//子线程
//最后结果是456而不是123,不管是主线程还是子线程都能影响UI线程
}
});
}
}
ViewModel
不再介绍,是一个持续的后台数据类,详解见MVVM模式
这里:MutableLiveData是LiveData的具体类;