本文將對Lifecycle-aware Components
三大組件之一的LiveData
進行分析蛉签。
首先,分析一下LiveData
類的結(jié)構(gòu):
可以看出浅浮,
LiveData
給出的方法主要分為以下兩類:
- 添加刪除observer
- 更新本身存儲的數(shù)據(jù)
接下來將對這兩個方面入手分析LiveData
工作機制
添加刪除observer
添加observer有兩個方法
observeForever(@NonNull Observer<T> observer)
-
observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer)
方法一是將一個生命周期不會變化(保持Lifecycle.Event.ON_RESUME
狀態(tài))的LifecycleOwner
作為參數(shù)調(diào)用的方法二:
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// 進入DESTROYED狀態(tài)無需繼續(xù)
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && existing.owner != wrapper.owner) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
}
class LifecycleBoundObserver implements GenericLifecycleObserver {
public final LifecycleOwner owner;
public final Observer<T> observer;
public boolean active;
public int lastVersion = START_VERSION;
LifecycleBoundObserver(LifecycleOwner owner, Observer<T> observer) {
this.owner = owner;
this.observer = observer;
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(observer);
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
}
void activeStateChanged(boolean newActive) {
if (newActive == active) {
return;
}
active = newActive;
boolean wasInactive = LiveData.this.mActiveCount == 0;
LiveData.this.mActiveCount += active ? 1 : -1;
if (wasInactive && active) {
onActive();
}
if (LiveData.this.mActiveCount == 0 && !active) {
onInactive();
}
if (active) {
dispatchingValue(this);
}
}
}
首先將observer封裝成一個LifecycleBoundObserver
對象添加到mObservers中去柠偶,和前面介紹的LifecycleRegistry
如出一轍别伏,之后將封裝后的observer同時注冊到對應(yīng)的LifecycleOwner
中去吐根,此時依據(jù)上節(jié)內(nèi)容,LifecycleRegistry
會將LifecycleBoundObserver
進行進一步封裝成為ObserverWithState
赠尾,在生命周期發(fā)生變化時力穗,通過調(diào)用dispatchEvent(LifecycleOwner owner, Event event)
方法通知observer生命周期變更,從而讓LifecycleBoundObserver
感知生命周期气嫁,在DESTROYED
狀態(tài)下自動移除当窗。
刪除observer與添加邏輯相同,只是多了一步將observer激活狀態(tài)改為false寸宵,對LiveData
內(nèi)部統(tǒng)計數(shù)據(jù)(mActiveCount)進行更改超全。
LiveData值的刷新
LiveData
提供了兩種方法對其進行賦值:
- setValue(T value)(主線程賦值)
- postValue(T value)(子線程賦值)
setValue(T value)
首先先對主線程賦值進行一個了解:
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
private void dispatchingValue(@Nullable LifecycleBoundObserver initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (initiator != null) {
considerNotify(initiator);
initiator = null;
} else {
for (Iterator<Map.Entry<Observer<T>, LifecycleBoundObserver>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
private void considerNotify(LifecycleBoundObserver observer) {
if (!observer.active) {
return;
}
if (!isActiveState(observer.owner.getLifecycle().getCurrentState())) {
observer.activeStateChanged(false);
return;
}
if (observer.lastVersion >= mVersion) {
return;
}
observer.lastVersion = mVersion;
//noinspection unchecked
observer.observer.onChanged((T) mData);
}
主要方法在dispatchingValue(@Nullable LifecycleBoundObserver initiator)
中:
- mDispatchingValue -> true代表之前有值刷新尚未廣播完成,將mDispatchInvalidated改為true邓馒,為false則直接向下進行嘶朱;
- 將mDispatchingValue設(shè)為true表示正在廣播,隨后判斷是對單個observer進行通知或者對所有監(jiān)聽此項的observer進行通知光酣。此時若有新值需要廣播疏遏,則在對所有監(jiān)聽此項observer進行通知時直接退出重新遍歷發(fā)送最新值。
considerNotify(LifecycleBoundObserver observer)
方法則是根據(jù)當(dāng)前項的激活狀態(tài)決定是移除observer還是將值變化通知對應(yīng)observer進行改變救军。
postValue(T value)
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
private final Runnable mPostValueRunnable = new Runnable() {
@Override
public void run() {
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;
mPendingData = NOT_SET;
}
//noinspection unchecked
setValue((T) newValue);
}
};
postValue(T value)
則是先暫時將新值保存财异,隨后將具體調(diào)用setValue
方法post到一個依附于主線程的Handle
中去,通過Handle
達到線程切換目的從而通知值刷新唱遭。
使用
LiveData
使用時主要是使用子類MutableLiveData
戳寸,這個子類實現(xiàn)了Livedata
并公開了兩個賦值方法。
小結(jié)
LiveData
的工作流程在有了之前LifecycleRegistry
的分析之后變得很清晰:主要是將observer封裝后存儲拷泽,并依托LifecycleRegistry
根據(jù)生命周期和自身值變化達到刷新通知observer進行刷新目的疫鹊。