使用

创建ViewModel

//继承ViewModel,创建LiveData
public class NameViewModel extends AndroidViewModel {

    private MutableLiveData<String> liveData;

    public MutableLiveData<String> getData() {
        if (liveData== null) {
            liveData= new MutableLiveData<String>();
        }
        return liveData;
    }

}

注册Observer

//注册观察者,监听LiveData数据变化
viewModel.getData().observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        mainFragmentText.setText(s);
    }
});

设置数据

//设置数据
if (viewModel.getData().getValue() != null && viewModel.getData().getValue().equals("world")) {
    viewModel.getData().setValue("hello");
} else {
    viewModel.getData().setValue("world");
}

- 阅读剩余部分 -

对于LifeCycle的简单使用可以看上一篇文章:LiveData+ViewModel+Repository搭建MVVM

这篇文章主要是为了阅读源码,尽量深入阅读,能力还是一般,见谅:

LifeCycle的作用

解决onCreate等生命周期方法,由于各种原因,后期越来越臃肿的问题。

关键类阐述

LifecycleRegistryOwner/LifecycleOwner

在Activity等组件生命周期发生变化的时候,发出相应的Event给LifecycleRegistry。

LifecycleRegistry

控制state的转换、接受分发Event事件。

LifecycleObserver

通过注解绑定Event和自定义的函数,实现对生命周期的监听并处理。

Event

@SuppressWarnings("WeakerAccess")
public enum Event {
    /**
     * Constant for onCreate event of the {@link LifecycleOwner}.
     */
    ON_CREATE,
    /**
     * Constant for onStart event of the {@link LifecycleOwner}.
     */
    ON_START,
    /**
     * Constant for onResume event of the {@link LifecycleOwner}.
     */
    ON_RESUME,
    /**
     * Constant for onPause event of the {@link LifecycleOwner}.
     */
    ON_PAUSE,
    /**
     * Constant for onStop event of the {@link LifecycleOwner}.
     */
    ON_STOP,
    /**
     * Constant for onDestroy event of the {@link LifecycleOwner}.
     */
    ON_DESTROY,
    /**
     * An {@link Event Event} constant that can be used to match all events.
     */
    ON_ANY
}

- 阅读剩余部分 -

什么是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的生命周期



- 阅读剩余部分 -

百分比:0% HEX: 00
百分比:1% HEX: 30
百分比:2% HEX: 50
百分比:3% HEX: 80
百分比:4% HEX: A0
百分比:5% HEX: D0
百分比:6% HEX: F0
百分比:7% HEX: 12
百分比:8% HEX: 14
百分比:9% HEX: 17










- 阅读剩余部分 -