LiveData与ViewModel

介绍

LiveData 是一种持有可被观察数据的类(an observable data holder class)。和其他可被观察的类不同的是,LiveData是有生命周期感知能力的(lifecycle-aware,),这意味着它可以在 activities, fragments, 或者 services 生命周期是活跃状态时更新这些组件。

用法

1.继承ViewModel
2.将实例类封装成MutableLiveData类型

基础代码如下

public class UserViewModel extends ViewModel {
    private MutableLiveData<User> mutableLiveData;
    String name = "asdasdasdadadada";

    public MutableLiveData<User> getData(){
        if (null == mutableLiveData){
            mutableLiveData = new MutableLiveData<>();
        }
        mutableLiveData.setValue(loadData());
        return this.mutableLiveData;
    }

    private User loadData() {
        User user = new User();
        user.age = new Random().nextInt(50);
        user.name = name.substring(0,new Random().nextInt(15));
        Log.d("UserViewModel",user.toString());
        return user;
    }

    public void change(){
        if(mutableLiveData != null){
            mutableLiveData.setValue(loadData());
        }
    }
}

界面上使用:

userViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()).create(UserViewModel.class);
        userViewModel.getData().observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                tv.setText(user.toString());
            }
        });

当改变调用change改变MutableLiveData的值时,界面会同步改变。

简单看下关联的代码:
当我们点击的时候会调用我们自己写的change方法,触发MutableLiveData的setValue方法:

    protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }

setValue方法中会触发分发的方法dispatchingValue:

void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
                considerNotify(initiator);
                initiator = null;
            } else {
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

该方法最终会执行considerNotify方法:

    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
        // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
        //
        // we still first check observer.active to keep it as the entrance for events. So even if
        // the observer moved to an active state, if we've not received that event, we better not
        // notify for a more predictable notification order.
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        //noinspection unchecked
        observer.mObserver.onChanged((T) mData);
    }

最后一句代码ObserverWrapper.mObserver就是我们在界面中设置的Observer对象,因此最终回调会返回到onChanged触发界面更新。

注意点

LiveData与MutableLiveData区别

LiveData与MutableLiveData的其实在概念上是一模一样的.唯一几个的区别如下:

1.MutableLiveData的父类是LiveData
2.LiveData在实体类里可以通知指定某个字段的数据更新.
3.MutableLiveData则是完全是整个实体类或者数据类型变化后才通知.不会细节到某个字段

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容