Android架构组件_LiveData

LiveData Overview   Part of Android Jetpack.
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.

Note: To import LiveData components into your Android project, see Adding Components to your Project.
LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes.

You can register an observer paired with an object that implements the LifecycleOwner interface. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED. This is especially useful for activities and fragments because they can safely observe LiveData objects and not worry about leaks—activities and fragments are instantly unsubscribed when their lifecycles are destroyed.

首先看一下官网给的介绍,意思就是LiveData是一个可观察的数据持有类,观察者的生命周期处于活动状态才会接收到数据更改的通知,可以通过注册 LifecycleOwner,监听页面的生命周期,也就是和activity或者fragment的生命周期绑定,页面销毁时,自动取消监听.

优点:

1.当页面处于活动状态时,监听的数据发生改变时,可以实时更新UI,当页面处于非活动状态时,页面不会监听数据变化,当处于非活动的页面再次变为活动状态时,页面会接受到最新的数据,并更新UI

2.不需要手动管理生命周期

3.所以在绑定Lifecycle后,观察者会在页面销毁时自动clear,不会造成内存泄漏,不会发生崩溃

4.数据共享

现在开始看怎么写代码

先配置gradle

annotationProcessor "android.arch.lifecycle:compiler:1.1.0"
implementation "android.arch.lifecycle:extensions:1.1.0"

首先创建一个LiveData对象(推荐DCL单例),它可以与任何数据一起使用,于是在这里放了一个Bean对象的List,来监听他的变化,这里的bean对象就是一个实体类

public class InfoViewModel extends ViewModel {

    private MutableLiveData<List<InfoBean>> mInfos;
    public MutableLiveData<List<InfoBean>> getInfo(){
        if (infos == null){
            mInfos = new MutableLiveData<>();
        }
        return mInfos;
    }
}

封装LiveData更改数据跟监听数据的方法,先通过ViewModelProviders拿到我们上面写的InfoViewModel,通过viewmodel对象去更改数据,监听数据变化

public class InfoDataObserver {
    public static InfoViewModel mInfoModel;
    private static FragmentActivity mcontext;
    private static InfoDataObserver instence;
    public static InfoDataObserver getInstence(FragmentActivity context) {
        mcontext = context;
        if (instence == null) {
            instence = new InfoDataObserver();
        }
            if (mInfoModel == null) {
                //拿到ViewModel对象
                mInfoModel = ViewModelProviders.of(context).get(InfoViewModel.class);
            }
        return instence;
    }

    public void changeData(List<InfoBean> list) {
        /**
         * postValue跟setValue的区别
         * setValue方法调用必须发生在主线程
         * postValue可以发生在子线程
         */
        mInfoModel.getInfo().postValue(list);
    }
    public void getChangeData(Observer<List<InfoBean>> observer) {
        mInfoModel.getInfo().observe(mcontext, observer);
    }
}

这里需要注意的是更改数据的时候调用的两个方法setValue()跟postValue(),两者都可以实现对数据的更改,但是setValue()只能在主线程执行,postValue()可以在子线程执行

推荐在页面的onCreate()中去创建Observer

InfoDataObserver.getInstence(MainActivity.this).getChangeData(new Observer<List<InfoBean>>() {
    @Override
    public void onChanged(@Nullable List<InfoBean> infoBeans) {
        Toast.makeText(MainActivity.this,"数据改变了",Toast.LENGTH_LONG).show();
    }
});

下面点击按钮更改数据,数据变化,上面的observer将会执行onChanged,参数就是变化的数据

String age = String.valueOf(new Random().nextInt(100));
InfoBean user = new InfoBean("hgy", age,"bj");
List<InfoBean> infoBeans = new ArrayList<>();
infoBeans.add(user);
InfoDataObserver.getInstence(MainActivity.this).changeData(infoBeans);

这里的changeData方法可以在A页面调用,在B页面C页面D页面等注册观察者,注册此观察者的页面都可以监听到数据的变化

搞定......

猜你喜欢

转载自blog.csdn.net/CSDN_15166447949/article/details/83537836