共计 2426 个字符,预计需要花费 7 分钟才能阅读完成。
先看 LifecycleEventObserver
的源码文档形容
/**
* Class that can receive any lifecycle change and dispatch it to the receiver.
* <p>
* If a class implements both this interface and
* {@link androidx.lifecycle.DefaultLifecycleObserver}, then
* methods of {@code DefaultLifecycleObserver} will be called first, and then followed by the call
* of {@link LifecycleEventObserver#onStateChanged(LifecycleOwner, Lifecycle.Event)}
* <p>
* If a class implements this interface and in the same time uses {@link OnLifecycleEvent}, then
* annotations will be ignored.
*/
public interface LifecycleEventObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
文档很分明的阐明了,如果一个观察者同时实现了 DefaultLifecycleObserver
和DefaultLifecycleObserver
,DefaultLifecycleObserver
要先于 LifecycleEventObserver
的onStateChanged
调用。如果也增加了 OnLifecycleEvent
注解。那么注解会被疏忽掉。
上面通过查看源码来证实。
从 getLifecycle().addObserver(LifecycleObserver)
开始。Lifecycle
的实现类是LifecycleRegistry
。
//LifecycleRegistry.java
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
statefulObserver.dispatchEvent(lifecycleOwner, event);
}
在创立 ObserverWithState
对象时,会通过 Lifecycling.lifecycleEventObserver(observer)
生成 LifecycleEventObserver
对象。
//Lifecycling.java
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {return (LifecycleEventObserver) object;
}
}
能够看到如果一个观察者同时实现了 DefaultLifecycleObserver
和DefaultLifecycleObserver
,返回的 LifecycleEventObserver
对象的理论类型是FullLifecycleObserverAdapter
。
再看ObserverWithState.dispatchEvent(lifecycleOwner, event);
//ObserverWithState.java
void dispatchEvent(LifecycleOwner owner, Event event) {State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
这里的 mLifecycleObserver
就是 FullLifecycleObserverAdapter
类型。所以最终调用的是 FullLifecycleObserverAdapter
的onStateChanged
。通过查看源码即可证实文章结尾的文档阐明。