生命周期变化时调用 LiveData.dispatchingValue
在调用 observe 时,我们需要传入 LifecycleOwner 和 Observer,在 observe 方法内部通过 LifecycleBoundObserver 将 Observer 和 LifecycleOwner 关联,并监听 LifecycleOwner 状态
public void observe(LifecycleOwner owner, Observer<? super T> observer) {
assertMainThread("observe");
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
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);
}
LifecycleBoundObserver 实现了 onStateChanged 接口,内部通过 LifecycleOwner 获取当前声明周期,如果是 DESTROYED 状态,则调用 LiveData.removeObserver,否则继续调用 activeStateChanged 方法
void activeStateChanged(boolean newActive) {
if (newActive == mActive) {
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
mActive = newActive;
changeActiveCounter(mActive ? 1 : -1);
if (mActive) {
dispatchingValue(this);
}
}
在 activeStateChanged 方法中,如果当前 Lifecycle 是 active 状态,继续调用 dispatchingValue 方法
setData 方法调用 LiveData.dispatchingValue
LiveData 主动更新数据的入口是 setData 方法,首先版本信息加一,然后调用 dispatchingValue 方法:
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
我们继续看 dispatchingValue 的具体实现
void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (initiator != null) {
considerNotify(initiator);
initiator = null;
} else {
for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
其实 LiveData 类中只是维护了 mObservers 信息,并提供了一些工具方法,dispatchingValue 最终调用 considerNotify(Observer)
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;
observer.mObserver.onChanged((T) mData);
}
在 considerNotify 中,如果 Observer 的版本号没有变化,则不更新(对应声明周期变化的路径),否则修改 mLastVersion,进而调用 Observer.onChanged 方法
总结:生命周期变化以及调用 setData 时会调用 LiveData.dispatchingValue,遍历 Observer,判断 Observer 的状态以及版本号信息,来判断是否通知数据变化