美文网首页jetpack
Android LiveData基本介绍

Android LiveData基本介绍

作者: 大聪明的博客 | 来源:发表于2022-08-17 16:45 被阅读0次

LiveData是Android Jetpack包提供的具有感知应用生命周期的组件,LiveData有两个子类分辨是MutableLiveData和MediatorLiveData,MutableLiveData针对单个需要观察的数据进行了封装,而MediatorLiveData则是可以观察其它的LiveData。开发过程中我们通常使用LiveData的子类,而不是去继承LiveData。
接下来我看下MutableLiveData的使用方法,

  private void liveDataTest(){
       MutableLiveData<String> mutableLiveData = new MutableLiveData<>();
       mutableLiveData.observe(this, s -> {
           //如果数据有变化的话,这里会接收到通知,所以我们在这里可以做一些反应。
       });
      mutableLiveData.setValue("我的值变化了");
    }

通过上面简单的例子我们了解了LiveData使用方法,但是LiveData是怎么做到这些的呢,接下来我们看下LiveData的源码分析一数据的观察流程。首先是observe方法;

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
//这里要求我们只能在主线程调用这个方法
        assertMainThread("observe");
//如果这个方法调用时,owner已经是DESTROYED状态则不会再往下执行了;
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
//LifecycleBoundObserver 是内部类,这个内部类处理了LifecycleOwner传递过来的生命周期事件
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
//同一个观察者不能观察不同的LifecycleOwner
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        owner.getLifecycle().addObserver(wrapper);
    }
 

通过上述代码分析我们知道,LiveData对LivecycleOwner注册了监听,在接收到宿主生命周期变化时,LiveData有机会去处理。接着我们看下setValue方法

//setValue方法要求在主线程调用,在其他线程使用postValue
    @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
       //辅助做数据是否有更新的判断
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }

//这个方法是实现数据分发的主要逻辑;
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
     //如果当前正在做数据分发,则不做重复处理
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
      //标记事件分发状态为true
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
               //observe方法被调用时,从这里触发分发
                considerNotify(initiator);
                initiator = null;
            } else {
          //setValue触发遍历观察改LiveData的所有观察者,分发setValue事件。
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

//该方法针对每个观察者做处理,判断是否需要分发和完成分发事件
    private void considerNotify(ObserverWrapper observer) {
        //如果观察者不活跃就放弃分发,观察者活跃的逻辑是处于STARTED和RESUMED之间。
        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;
       //调用观察者的onChanged事件完成分发。
        observer.mObserver.onChanged((T) mData);
    }

通过以上方法我们知道了,LiveData如何封装LifeCyclerOwner和Observer的,以及setValue的调用流程。对LiveData有了基础的了解。

相关文章

网友评论

    本文标题:Android LiveData基本介绍

    本文链接:https://www.haomeiwen.com/subject/dwwjgrtx.html