Android LiveData基本介紹

LiveData是Android Jetpack包提供的具有感知應(yīng)用生命周期的組件,LiveData有兩個(gè)子類(lèi)分辨是MutableLiveData和MediatorLiveData,MutableLiveData針對(duì)單個(gè)需要觀察的數(shù)據(jù)進(jìn)行了封裝,而MediatorLiveData則是可以觀察其它的LiveData。開(kāi)發(fā)過(guò)程中我們通常使用LiveData的子類(lèi),而不是去繼承LiveData。
接下來(lái)我看下MutableLiveData的使用方法,

  private void liveDataTest(){
       MutableLiveData<String> mutableLiveData = new MutableLiveData<>();
       mutableLiveData.observe(this, s -> {
           //如果數(shù)據(jù)有變化的話,這里會(huì)接收到通知,所以我們?cè)谶@里可以做一些反應(yīng)。
       });
      mutableLiveData.setValue("我的值變化了");
    }

通過(guò)上面簡(jiǎn)單的例子我們了解了LiveData使用方法,但是LiveData是怎么做到這些的呢,接下來(lái)我們看下LiveData的源碼分析一數(shù)據(jù)的觀察流程。首先是observe方法;

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
//這里要求我們只能在主線程調(diào)用這個(gè)方法
        assertMainThread("observe");
//如果這個(gè)方法調(diào)用時(shí),owner已經(jīng)是DESTROYED狀態(tài)則不會(huì)再往下執(zhí)行了;
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
//LifecycleBoundObserver 是內(nèi)部類(lèi),這個(gè)內(nèi)部類(lèi)處理了LifecycleOwner傳遞過(guò)來(lái)的生命周期事件
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
//同一個(gè)觀察者不能觀察不同的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);
    }
 

通過(guò)上述代碼分析我們知道,LiveData對(duì)LivecycleOwner注冊(cè)了監(jiān)聽(tīng),在接收到宿主生命周期變化時(shí),LiveData有機(jī)會(huì)去處理。接著我們看下setValue方法

//setValue方法要求在主線程調(diào)用,在其他線程使用postValue
    @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
       //輔助做數(shù)據(jù)是否有更新的判斷
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }

//這個(gè)方法是實(shí)現(xiàn)數(shù)據(jù)分發(fā)的主要邏輯;
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
     //如果當(dāng)前正在做數(shù)據(jù)分發(fā),則不做重復(fù)處理
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
      //標(biāo)記事件分發(fā)狀態(tài)為true
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
               //observe方法被調(diào)用時(shí),從這里觸發(fā)分發(fā)
                considerNotify(initiator);
                initiator = null;
            } else {
          //setValue觸發(fā)遍歷觀察改LiveData的所有觀察者,分發(fā)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;
    }

//該方法針對(duì)每個(gè)觀察者做處理,判斷是否需要分發(fā)和完成分發(fā)事件
    private void considerNotify(ObserverWrapper observer) {
        //如果觀察者不活躍就放棄分發(fā),觀察者活躍的邏輯是處于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;
        }
      //如果改觀察者已經(jīng)接受過(guò)數(shù)據(jù)了,也不再進(jìn)行分發(fā)
        if (observer.mLastVersion >= mVersion) {
            return;
        }
       //對(duì)觀察者進(jìn)行分發(fā)版本記錄
        observer.mLastVersion = mVersion;
       //調(diào)用觀察者的onChanged事件完成分發(fā)。
        observer.mObserver.onChanged((T) mData);
    }

通過(guò)以上方法我們知道了,LiveData如何封裝LifeCyclerOwner和Observer的,以及setValue的調(diào)用流程。對(duì)LiveData有了基礎(chǔ)的了解。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容