LiveData了解一下

什么是LiveData

它可以用來持有 可被觀察的數(shù)據(jù),可以感知到UI組件的生命周期,只有組件處于活動(STARTED和RESUMED)狀態(tài)時(shí),LivedData才可以用來更新數(shù)據(jù)。當(dāng)組件DESTROYED的時(shí)候,它會自動移出,不會引起內(nèi)存泄露

關(guān)注以下幾個(gè)類

  1. LiveData
    ObserverWrapper
    LifecycleBoundObserver: (實(shí)現(xiàn)GenericLifecycleObserver接口)
  2. GenericLifecycleObserver: 一個(gè)接口,感知組件生命周期的變化,通知給觀察者
  3. LifecycleRegistry (Lifecycle的子類)

Demo

public class NameViewModel extends ViewModel {
    //MutableLiveData 是LiveDaTa的子類
    private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getCurrentName() {
        if(mCurrentName==null){
            mCurrentName = new MutableLiveData<>();
        }
        return mCurrentName;
    }
}
public class NameActvity extends AppCompatActivity {
    private NameViewModel mModel;
    private TextView mNameTv;
    private Button mBtn;
    private String[] names = {"張三", "李四", "王麻子"};


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name);
        mNameTv = (TextView) findViewById(R.id.nameTv);
        mBtn = (Button) findViewById(R.id.btn);
        //1. 通過反射獲得NameViewModel,不關(guān)注這個(gè)
        mModel = ViewModelProviders.of(this).get(NameViewModel.class);
        //2. 實(shí)現(xiàn)觀察者(lifecycle包下的接口)
        Observer<String> nameObserver = new Observer<String>() {
            //每次數(shù)據(jù)更新都會自動回調(diào)
            @Override
            public void onChanged(@Nullable String s) {
                mNameTv.setText(s);
            }
        };
        //3.為LiveData添加觀察者 
        重點(diǎn)看這里(組件必須實(shí)現(xiàn)了LifecycleOwner ,所以LivdeData還是要結(jié)合Lifecycle使用),進(jìn)入源碼
        mModel.getCurrentName().observe(this, nameObserver);


        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int random = (int) (Math.random() * 3);
                String name = names[random];
                //4.推送信息(只能在主線程,其他用postValue())
                mModel.getCurrentName().setValue(name);
            }
        });

    }
}

源碼

LiveData

 @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
      //組件當(dāng)前狀態(tài)為DESTROYED,不添加觀察者
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
    //LifecycleBoundObserver 是ObserverWrapper 的包裝類
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //以observer為key,wrapper為value關(guān)聯(lián)存入,如果之前有關(guān)聯(lián)直接返回wrapper,如果沒有,存入且返回Null,
        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;
        }
      最終是通過Lifecycle來添加觀察者
     進(jìn)入LifecycleRegistry
        owner.getLifecycle().addObserver(wrapper);
    }

LifecycleRegistry

 @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        //添加觀察者的時(shí)候只區(qū)分兩種狀態(tài) 不是銷毀 就是 新生
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        //如果之前添加過,就結(jié)束
        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        //如果組件生命周期結(jié)束,就結(jié)束
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        //計(jì)算目標(biāo)觀察者的狀態(tài)
        State targetState = calculateTargetState(observer);
        //添加的過觀察者計(jì)數(shù)器
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            分發(fā)事件
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }

分發(fā)事件
LifecycleRegistry->ObserverWithState

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            生命周期狀態(tài)改變的回調(diào)
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    

生命周期狀態(tài)改變的回調(diào)
LiveData->LifecycleBoundObserver

  @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
           活動狀態(tài)改變的回調(diào)
            activeStateChanged(shouldBeActive());
        }

活動狀態(tài)改變的回調(diào)
LiveData->ObserverWrapper


        void activeStateChanged(boolean newActive) {
            if (newActive == mActive) {
                return;
            }
            // immediately set active state, so we'd never dispatch anything to inactive
            // owner
            mActive = newActive;
            boolean wasInactive = LiveData.this.mActiveCount == 0;
            LiveData.this.mActiveCount += mActive ? 1 : -1;
            if (wasInactive && mActive) {
                onActive();
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            if (mActive) {
                傳遞 ObserverWrapper 
                dispatchingValue(this);
            }
        }

傳遞ObserverWrapper
LiveData

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

推送數(shù)據(jù) LiveData

 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
        觀察者獲得數(shù)據(jù)
        observer.mObserver.onChanged((T) mData);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • ??LiveData是一個(gè)可被觀察的數(shù)據(jù)持有者類。與常規(guī)的Observable不同,LiveData能意識到應(yīng)用程...
    鶴鶴閱讀 47,257評論 6 42
  • 示例應(yīng)用程序 使用LiveData的優(yōu)點(diǎn) 使用LiveData對象創(chuàng)建LiveData對象觀察LiveData對象...
    yyg閱讀 5,930評論 5 7
  • 前言: 作為一名移動互聯(lián)網(wǎng)App研發(fā)人員,在實(shí)際項(xiàng)目的研發(fā)過程中,保質(zhì)保量高效率,方便快捷,同時(shí)方便開發(fā)者之間的互...
    Yagami3zZ閱讀 4,789評論 1 9
  • 在Model - build.gradle添加依賴 LiveData是一個(gè)可觀察的數(shù)據(jù)持有者類。與常規(guī)可觀察性不同...
    貝貝beibei96閱讀 1,469評論 0 1
  • 前言 系列文章 Android Architecture Component之Lifecycle-Aware Co...
    Jason騎蝸牛看世界閱讀 3,747評論 4 11

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