前言
在Android推出的架構(gòu)組件Architecture Components
中,LiveData和ViewModel無疑是最核心的。它們最神奇的地方就在于:
- LiveData:能夠在數(shù)據(jù)發(fā)生變化時及時通知View去更新界面,并且如果當界面不可見或者被銷毀時刨秆,LiveData是不會通知UI的降宅。言下之意,LiveData是能夠感知生命周期的已卸。
- ViewModel:它能夠為我們保存數(shù)據(jù),即使Activity由于某些原因需要重建镇眷,保存在ViewModel中的數(shù)據(jù)也不會因此被銷毀咬最。這帶來的好處就是頁面重建后,數(shù)據(jù)無需重新加載欠动,直接用原來保存下來的數(shù)據(jù)即可永乌。
但其實在它們的背后還有一個默默付出的Lifecycle,可以說Lifecycle才是這個架構(gòu)的靈魂具伍。
Lifecycle
前面說了翅雏,LiveData是可以感知Android生命周期的,而LiveData是通過Lifecycle來感知生命周期的人芽。從Lifecycle的字面意思來看望几,它就是跟生命周期有直接關(guān)系的。我們知道萤厅,具有Android生命周期的最常見的就是Activity和Fragment橄抹。所以要想了解LiveData,需要先了解Android的生命周期是如何傳遞給Lifecycle的才行惕味。下面這些例子都是以Fragment來展開分析的楼誓。
在剛接觸這個框架的時候,出現(xiàn)了很多與Lifecycle有關(guān)的類名挥,比如說:LifecycleOwner
, LifeCycle
, LifecycleRegistry
, LifecycleObserver
...講真的疟羹,對于一個不熟悉的東西,一下子又扔過來這么幾個看起來有點關(guān)聯(lián)的東西禀倔,頭是有點大的榄融。所以有必要花些時間來理一理這些東西先。先上一張類圖(這里只是把一些比較重要的屬性和方法羅列出來):
- LifecycleOwner:這是一個接口救湖,它只有一個方法
getLifecycle()
愧杯。從名字上理解它就是一個擁有生命周期的組件,比如說Fragment鞋既,所以Fragment實現(xiàn)了這個接口民效,也可以這么理解,F(xiàn)ragment就是一個生命周期的擁有者涛救。 - Lifecycle:這是一個抽象類畏邢。主要是添加和移除觀察者,和獲得當前生命周期的狀態(tài)检吆。它還有兩個內(nèi)部的枚舉類:State和Event舒萎,分別表示生命周期的狀態(tài)和相應(yīng)的事件。
- LifecycleObserver:這是一個接口蹭沛,并且是空的臂寝,暫時知道它是一個觀察者就好了章鲤。
- LifecycleRegistry:這個類繼承了Lifecycle類并實現(xiàn)了所有的方法。成員變量
mObserverMap
用來管理觀察者隊列咆贬。handleLifecycleEvent()
方法用來設(shè)置當前的生命周期狀態(tài)败徊,并通知觀察者更新狀態(tài)。LifecycleOwner需要通過handleLifecycleEvent()
這個方法掏缎,將自己的生命周期狀態(tài)傳遞給Lifecycle皱蹦,從而讓Lifecycle擁有感知生命周期的能力。 - Fragment:它有一個
mLifecycleRegistry
屬性, 類型正是Lifecycle眷蜈。實現(xiàn)的getLifecycle()
就是返回了mLifecycleRegistry
沪哺。
用一句話來解釋它們之間的聯(lián)系就是:Fragment是一個LifecycleOwner,它在自己的生命周期的各個階段中酌儒,通過mLifecycleRegistry
辜妓,將自己的狀態(tài)告訴了Lifecycle,讓Lifecycle擁有了感知生命周期的能力忌怎。
講到這里了籍滴,再來深入一下研究LifecycleRegistry$handleLifecycleEvent()
這個方法吧×裥ィ看之前得先知道下mObserverMap
的結(jié)構(gòu)孽惰。
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
這是一個特殊的Map,它能夠在遍歷的時候執(zhí)行添加或者刪除操作插掂。它的key值是LifecycleObserver灰瞻,沒什么好說的腥例。value值是ObserverWithState辅甥,在addObserver()
的時候,會將LifecycleObserver和初始狀態(tài)State封裝成一個ObserverWithState然后放進value值中燎竖。OK璃弄,這只是一個小插曲而已,有助于我們后面的理解构回,接著進入正題吧夏块。
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
收到一個事件后,根據(jù)當前的事件獲取下一個狀態(tài)纤掸,然后跳轉(zhuǎn)到下一個狀態(tài)脐供。
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
代碼也很簡單,一眼就能看出重點在sync()
方法上借跪。
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
+ "new events from it.");
return;
}
while (!isSynced()) {
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
方法內(nèi)先是判斷LifecycleOwner是否被回收政己,接著再判斷所有的觀察者狀態(tài)是否都同步了。判斷依據(jù)是最新的觀察者和最老的觀察者之間狀態(tài)是否一致掏愁。
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
如果還沒有完成同步歇由,則走while循環(huán)繼續(xù)同步卵牍。可以看到循環(huán)體內(nèi)有backwardPass()
和forwardPass()
沦泌,我們只看一個就好了糊昙,之所以會有兩個,是因為FastSafeIterableMap這個數(shù)據(jù)結(jié)構(gòu)的特性決定的谢谦。
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
外面的都是一些判斷释牺,直接看到observer.dispatchEvent(lifecycleOwner, event)
這里,看到dispatchXXX
有沒有覺得有點熟悉和激動他宛?需要注意的是這里的observer
是一個ObserverWithState來著船侧。
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
看到這里,總算可以有個了結(jié)了厅各。LifecycleObserver通過onStateChanged()
方法將狀態(tài)改變發(fā)送給了觀察者镜撩,觀察者由此可以得知Android生命周期的變化。
等等队塘,好像哪里不對袁梗。上面不是說LifecycleObserver是一個空接口嗎?怎么這里就冒出了onStateChanged()
這個方法來了憔古?這不是打自己的臉嗎遮怜?
其實這里的LifecycleObserver是一個LifecycleEventObserver,也是一個接口來著鸿市,繼承了LifecycleObserver锯梁,另外還有一個FullLifecycleObserver也繼承了LifecycleObserver。
展望未來
這里僅僅只是做了一個開篇焰情,為接下來分析LiveData和ViewModel做鋪墊陌凳,為了不讓自己拖太久,先來一篇Lifecycle的分析打打雞血内舟。