@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
//获取当前生命周期状态
Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
//如果组件已销毁了,就移除观察
if (currentState == DESTROYED) {
removeObserver(mObserver);
return;
}
Lifecycle.State prevState = null;
while (prevState != currentState) {
prevState = currentState;
activeStateChanged(shouldBeActive());
currentState = mOwner.getLifecycle().getCurrentState();
}
}
/* 判断是否绑定 */
@Override
boolean isAttachedTo(LifecycleOwner owner) {
return mOwner == owner;
}
/* 移除观察 */
@Override
void detachObserver() {
mOwner.getLifecycle().removeObserver(this);
}
}
- ObserverWrapper 这个类里面有个方法,后面的粘性事件会用到,先看看。
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);
}
}
==========================================================