MVVM设计模式学习笔记(二)——结合LiveData来搭建MVVM

一. 初识LiveData

1. 什么是LiveData

LiveData是一个数据持有类,它的数据是可以被观察者订阅的,并且能够感知组件(Activity,Fragment,Service)的生命周期(但是必须是处于激活状态才会通知,激活状态:STARTED,RESUMED)。

2. 为什么要用LiveData

  • 保证数据和UI的统一:
    LiveData使用的是观察者模式,并且扮演的是被观察者的角色,当LiveData中的数据发生变化的时候,LiveData会通知观察者(UI)进行实时更新。
  • 减少内存泄漏:
    LiveData能够感知到组件的生命周期,当组件处于DEATROYED状态的时候,会将观察者对象清除掉。
  • 降低了crash的可能性:
    由于LiveData能够感知组件的生命周期的特性,在组件仍未处于激活状态的时候,LiveData并不会通知组件数据的变化。
  • 不需要额外的手动处理生命周期的变化:
    LiveData中自带的感知组件生命周期的功能,不需要开发者在代码中通知LiveData组件的生命周期的状态。
  • 数据和组件的分离:
    组件只负责UI,LiveData负责提供数据,在组件被重新创建的时候(比如屏幕方向的改变),数据由于存放在LiveData中,所以并不会被销毁。
  • 能够实现资源共享:
    可以通过定义一个继承自LiveDta的单例类实现,可以监听一些系统属性的变化。

在MVVM中,可以使用LiveData配合ViewModel实现业务需求。

二. 结合LiveData搭建MVVM框架

LiveData主要在ViewModel中进行使用,通过观察者模式来实现ViewModel通知View的更新。通常也会定义一个Repository类,来做网络请求,数据库查询等工作,可以减轻ViewModel层的代码量和复杂度,这样ViewModel层就能够专注的处理LiveData数据的处理工作了。使用LiveData的MVVM和使用dataBinding的MVVM结构有不同之处:


mvvm-live结构图

上代码说话~

这里新定义了一个SecondActivity的View层,定义了一个UserModel2作为View层的ViewModel,Model层依旧使用原来的UserModel。

1.ViewModel层

public class UserViewModel2 extends ViewModel {

    private UserRepository userRepository = new UserRepository();//Repository处理数据请求
    private MutableLiveData isRefresh = new MutableLiveData<>();

    LiveData userLiveData = Transformations.map(isRefresh, new Function() {
        @Override
        public  UserModel apply(Boolean input) {

            if (input){
                return userRepository.refresh();
            }else {
                return userRepository.init();
            }

        }
    });

    public UserViewModel2 setIsRefresh(boolean isRefresh){
        this.isRefresh.setValue(isRefresh);
        return this;
    }

    public LiveData getUserLiveData() {
        return userLiveData;
    }
}

在ViewModel层使用了LiveData和MutableLiveData来分别对数据进行了封装,以便于之后的使用,userLiveData使用了Transformations的map方法,用于在数据传递到观察者之前做出一些符合需求的变动。

  1. Repository类
public class UserRepository {

    //初始化数据
    public UserModel init(){
        MutableLiveData userModelData = new MutableLiveData<>();
        UserModel userModel = new UserModel();
        userModel.setId("111");
        userModel.setName("姓名1");
        userModelData.setValue(userModel);
        return userModel;
    }

    //更新数据
    public UserModel refresh(){
        MutableLiveData userModelData = new MutableLiveData<>();
        UserModel userModel = new UserModel();
        userModel.setId("222");
        userModel.setName("姓名2");
        return userModel;
    }
}

UserRepository类用了init()和refresh()模拟对数据的操作。

  1. View层
class SecondActivity extends AppCompatActivity implements View.OnClickListener {

    private UserViewModel2 model ;
    private TextView tvID;
    private TextView tvName;
    private Button btnClick;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        tvID = findViewById(R.id.tv_id);
        tvName = findViewById(R.id.tv_name);
        btnClick = findViewById(R.id.btn_click);
        btnClick.setOnClickListener(this);

        model = ViewModelProviders.of(this).get(UserViewModel2.class);//获取ViewModel的实例
        //初始化数据的操作
        model.setIsRefresh(false).getUserLiveData().observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable UserModel userModel) {
                tvID.setText(userModel.getId());
                tvName.setText(userModel.getName());
            }
        });
    }

    @Override
    public void onClick(View v) {
        //更新数据的操作
        model.setIsRefresh(true);
    }
}

View层中通过调用ViewModel的方法来通知ViewModel需要做的工作,ViewModel中的LiveData数据可以通过实现observe方法来实现当数据变动则更新UI的操作。

相关笔记传送门:
MVVM设计模式学习笔记(一)——MVVM初体验
LiveData源码学习笔记

你可能感兴趣的:(MVVM设计模式学习笔记(二)——结合LiveData来搭建MVVM)