LifecycleEventObserver与DefaultLifecycleObserver的优先级
先看LifecycleEventObserver
的源码文档描述
/**
* Class that can receive any lifecycle change and dispatch it to the receiver.
* * 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)}
* * 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;
}
【LifecycleEventObserver与DefaultLifecycleObserver的优先级】这里的
mLifecycleObserver
就是FullLifecycleObserverAdapter
类型。所以最终调用的是FullLifecycleObserverAdapter
的onStateChanged
。通过查看源码即可证实文章开头的文档说明。推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- Docker应用:容器间通信与Mariadb数据库主从复制
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量
- 第326天
- Shell-Bash变量与运算符
- 逻辑回归的理解与python示例
- Guava|Guava RateLimiter与限流算法
- 我和你之前距离
- CGI,FastCGI,PHP-CGI与PHP-FPM
- 原生家庭之痛与超越