voidactiveStateChanged(boolean newActive) { if (newActive == mActive) { return; } // immediately set active state, so we'd never dispatch anything to inactive // owner mActive = newActive; //记录LiveData活跃观察者的数量 changeActiveCounter(mActive ? 1 : -1); //在LiveData活跃状态下立刻分发值 if (mActive) { dispatchingValue(this); } }
voiddispatchingValue(@Nullable ObserverWrapper initiator) { if (mDispatchingValue) { mDispatchInvalidated = true; return; } mDispatchingValue = true; do { mDispatchInvalidated = false; if (initiator != null) { // observer转成活跃状态立刻分发一次值 considerNotify(initiator); initiator = null; } else { //遍历observer分发值 for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator = mObservers.iteratorWithAdditions(); iterator.hasNext(); ) { considerNotify(iterator.next().getValue()); if (mDispatchInvalidated) { break; } } } } while (mDispatchInvalidated); mDispatchingValue = false; }
//回调observer的onChanged方法 privatevoidconsiderNotify(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; } //比较LiveData与Observer对象维护的版本号,一致就不在分发新值 //若不一致,回调onChanged分发新值(对于初始化的observer,其版本号为-1,只要LiveData中更 //新过版本号,那新的observer总是会在初始化后收到最新的值) observer.mLastVersion = mVersion; observer.mObserver.onChanged((T) mData); }