LiveData+ViewModel+Repository搭建MVVM

什么是LiveData

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
Source:https://developer.android.com/topic/libraries/architecture/livedata.html

什么是ViewModel

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
Source:https://developer.android.com/topic/libraries/architecture/viewmodel

ViewModel的生命周期

ViewModel的生命周期

写个Demo

引入依赖库

implementation "android.arch.lifecycle:extensions:1.1.1"

extensions库中包含的内容如下:

extensions库内容

整体架构

MVVM

步骤

创建Model,定义数据结构

public class MainBean {

    public DataBean data;

    public static class DataBean {
        public String name;
    }

}

创建Repository,获取数据并暴露接口给ViewModel

public MutableLiveData<MainBean> getData(int id) {
    //构造需要暴露的数据结构
    final MutableLiveData<MainBean> liveData = new MutableLiveData<>();
    //获取数据
    MainApiService mainApiService = retrofit.create(MainApiService.class);
    Call<MainBean> call = mainApiService.getData(id);
    call.enqueue(new Callback<MainBean>() {
        @Override
        public void onResponse(Call<MainBean> call, Response<MainBean> response) {
            //设置数据
            if (response.isSuccessful()) {
                liveData.setValue(response.body());
            } else {
                liveData.setValue(null);
            }
        }

        @Override
        public void onFailure(Call<MainBean> call, Throwable t) {
            liveData.setValue(null);
        }
    });
    //返回数据
    return liveData;
}

创建ViewModel,编写View层真正需要的接口

如果View层需要直接操作MainBean,可以这样处理:

public LiveData<MainBean> getData() {
    return mainRepository.getData();
}

如果View层只需要name字段,用于显示名字,可以这样处理:

public LiveData<String> getData() {
    int id = 1;
    final MutableLiveData<MainBean> liveData = mainRepository.getData(id);
    //执行数据转换操作并获得转换后的数据
    LiveData<String> newLiveData = Transformations.switchMap(liveData, new Function<MainBean, LiveData<String>>() {
        @Override
        public LiveData<String> apply(MainBean mainBean) {
            final MutableLiveData<String> newLiveData = new MutableLiveData<>();
            if (mainBean == null || mainBean.data == null) {
                newLiveData.setValue(null);
            } else {
                newLiveData.setValue(mainBean.data.name);
            }
            return newLiveData;
        }
    });
    //返回转换后的数据
    return newLiveData;
}

创建View层,仅执行UI显示逻辑,不可执行数据处理逻辑

mainViewModel.getData().observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        mainFragmentText.setText(s);
    }
});

完整代码,请看Github

什么是LifeCycle

上面的LiveData组件的核心实际上就是Lifecycle,比如我们想要监听Acitivity等组件的生命周期,就可以使用该类实现,下面介绍一下如何使用:

首先使Activity等组件实现LifecycleRegistryOwner(这个类实际上已经过时了,但是我仍实现他是因为实现LifecycleOwner在Fragment中会出现无法监听生命周期的问题)

public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner {

    private LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

    @NonNull
    @Override
    public LifecycleRegistry getLifecycle() {
        return lifecycleRegistry;
    }
}

创建LifecycleObserver类,监听生命周期变化

public class ActivityLifecycleObserver implements LifecycleObserver {

    private static final String TAG = "ActivityObserver";

    private Context context;

    public ActivityLifecycleObserver(Context context) {
        this.context = context;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        Log.d(TAG, "onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        Log.d(TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.d(TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.d(TAG, "onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        Log.d(TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
    }

    //任意回调都会调用它,比如调用完onCreate()后会回调这里的onCreate(),然后会回调onAny();
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void onAny() {
        Log.d(TAG, "onAny");
    }

}

注册

getLifecycle().addObserver(new ActivityLifecycleObserver(getApplicationContext()));

LifeCycle目前只写到这里,还没有继续深入,继续努力中...

参考文章

添加新评论