publicvoidobserve(@NonNullLifecycleOwnerowner,@NonNullObserver<?superT>observer){//判断是否是主线程assertMainThread("observe");//判断当前LifecycleOwner处于DESTORYED状态 直接返回if(owner.getLifecycle().getCurrentState()==DESTROYED){// ignorereturn;}//创建一个包装类LifecycleBoundObserverwrapper=newLifecycleBoundObserver(owner,observer);//key 是observer类 value 是包装类//如果已经存在putIfAbsent返回之前的value,不存在存储当前值并返回nullObserverWrapperexisting=mObservers.putIfAbsent(observer,wrapper);if(existing!=null&&!existing.isAttachedTo(owner)){//如果Observer类直接抛出异常thrownewIllegalArgumentException("Cannot add the same observer"+" with different lifecycles");}if(existing!=null){return;}owner.getLifecycle().addObserver(wrapper);}
privateabstractclassObserverWrapper{finalObserver<?superT>mObserver;booleanmActive;//是否处于活跃intmLastVersion=START_VERSION;ObserverWrapper(Observer<?superT>observer){mObserver=observer;}//是否活跃abstractbooleanshouldBeActive();//判断Observer是否和LifecycleOwner有绑定关系booleanisAttachedTo(LifecycleOwnerowner){returnfalse;}//移除ObservervoiddetachObserver(){}//活跃状态发生改变voidactiveStateChanged(booleannewActive){if(newActive==mActive){return;}// immediately set active state, so we'd never dispatch anything to inactive// ownermActive=newActive;//如果活跃数为0 则表示之前是不活跃状态booleanwasInactive=LiveData.this.mActiveCount==0;//如果是活跃的 活跃数+1 否则-1LiveData.this.mActiveCount+=mActive?1:-1;//不活跃变为活跃 调用onActive()if(wasInactive&&mActive){onActive();}//活跃数为0 变为不活跃调用onInactiveif(LiveData.this.mActiveCount==0&&!mActive){onInactive();}//分发数据if(mActive){dispatchingValue(this);}}}
@MainThreadpublicvoidobserveForever(@NonNullObserver<?superT>observer){assertMainThread("observeForever");//创建AlwaysActiveObserverAlwaysActiveObserverwrapper=newAlwaysActiveObserver(observer);ObserverWrapperexisting=mObservers.putIfAbsent(observer,wrapper);if(existinginstanceofLiveData.LifecycleBoundObserver){thrownewIllegalArgumentException("Cannot add the same observer"+" with different lifecycles");}if(existing!=null){return;}wrapper.activeStateChanged(true);}
privatevoidconsiderNotify(ObserverWrapperobserver){//如果Observer不是活跃的returnif(!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;}//如果mLastVersion大于等于mVersion直接返回if(observer.mLastVersion>=mVersion){return;}//修改版本号observer.mLastVersion=mVersion;//更新值observer.mObserver.onChanged((T)mData);}