LiveData 作为 View 的 UI 状态数据源,并不是在 LifecycleOwner 的每个生命周期状态中都可用的,而必须在 View 完成所有的测量和布局操作后,才能基于 LiveData 进行 UI 状态更新。这说明 LiveData 是有一个可用状态标记的,在源代码中,标记为 active:
LiveData 中更新 active 标记的方法:
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
这说明,只有当 LifecycleOwner 的状态至少是 STARTED,LiveData 才是处于激活状态的。再看 Lifecycle.State 的枚举顺序:
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
/**
-
Compares if this State is greater or equal to the given {@code state}.
-
@param state State to compare with
-
@return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
进一步说明,只有当 LifecycleOwner 的状态是 STARTED 和 RESUMED 时,LiveData 才是处于激活状态的,而只有在激活状态下,LiveData 才会将最新数据变化通知给它的订阅者:
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) { // 没有激活,不进行通知
return;
}
// 在 LifecycleOwner 的生命周期变化事件分派之前,需要提前主动更新一下激活状态,
// 如果未激活,同样不进行通知
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
//…省略非关键代码
observer.mObserver.onChanged((T) mData);
}
严格的说这里并不应该叫 LiveData 的激活状态,而应该是向 LiveData 进行订阅的 LifecycleOwner 的激活状态,此时 LifecycleOwner 作为观察者观察 LiveData 的变化。所以这里可能叫 LiveData 在每一个 LifecycleOwner 上的分身的激活状态更合适,为了表述方便,我们就统称叫 L