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ǔ)的了解。