先看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
。通过查看源码即可证实文章开头的文档说明。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。