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); }

文档很清楚的说明了,如果一个观察者同时实现了DefaultLifecycleObserverDefaultLifecycleObserverDefaultLifecycleObserver要先于LifecycleEventObserveronStateChanged调用。如果也添加了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; } }

可以看到如果一个观察者同时实现了DefaultLifecycleObserverDefaultLifecycleObserver,返回的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类型。所以最终调用的是FullLifecycleObserverAdapteronStateChanged。通过查看源码即可证实文章开头的文档说明。

    推荐阅读