虐面試官系列Lifecyele篇 – (4)源碼分析之響應的觀察者們
- 2020 年 2 月 17 日
- 筆記
前言:
原諒我標題黨??
Lifecycle系列:
虐面試官系列Lifecyele篇 – (2)源碼分析之 Event & State
虐面試官系列Lifecyele篇 – (3)源碼分析之註冊 & 發送
待完成:
虐面試官系列Lifecyele 篇 – (5)集成Lifecycle的幾種方式的源碼差別
又是很久很久沒寫文章了,最近打算寫下Android的又一基礎知識: Android 官方架構組件系列。打算把相關的知識點都整理寫下,所以本系列的主體為Lifecycle.



正文:
在上一篇虐面試官系列Lifecyele篇 – (3)源碼分析之註冊 & 發送中我們我們可以看到: 最後通過真正的觀察者進行方法調用進行回調通知:
mLifecycleObserver.onStateChanged(owner, event);
但是我們再平常使用的時候,貌似是這樣的:
class LifeObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void CCCC(LifecycleOwner owner) { } }
都沒有這個onStateChanged
方法,那這又是為什麼呢?
實際上這個mLifecycleObserver
並不是我們傳入的Observer
,而是中間適配器觀察者,它先接受到了通知,然後內部在調用我們自己寫的Observer
,進行發送通知。
簡單就是ObserverWithState.dispatchEvent ——> 含有onStateChanged(owner, event)方法的適配器觀察者AdapterObserver(如果我們傳入的Observer含有onStateChanged方法,比如GenericLifecycleObserver,則直接沒有中間這個適配器觀察者) ——> 具體我們寫的Observer
我們前面說過,我們的觀察者對象被通過addObserver方法被封裝到了,加入到了ObserverWithState對象裏面:
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { '//我們可以看到我們的傳入的Observer被getCallback轉成了其他的Observer(或者適配器):mLifecycleObserver' mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); '//可以看到最後的回調的時候是調用mLifecycleObserver的onStateChanged方法' mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }
我們來具體看下,我們的Observer到底被轉換成了哪些Observer:
@NonNull static GenericLifecycleObserver getCallback(Object object) { //'1. FullLifecycleObserver觀察者,同時返回FullLifecycleObserverAdapter適配器類' if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); } //'2. GenericLifecycleObserver觀察者,同時直接返回該類' if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; } final Class<?> klass = object.getClass(); //'把傳入的Observer通過getObserverConstructorType方法傳入判斷,是否有相應的生成的輔助類' int type = getObserverConstructorType(klass); //'如果有相應生成的輔助類' if (type == GENERATED_CALLBACK) { List<Constructor<? extends GeneratedAdapter>> constructors = sClassToAdapters.get(klass); //'只有一個構造器' if (constructors.size() == 1) { //'3. GeneratedAdapter適配器類' GeneratedAdapter generatedAdapter = createGeneratedAdapter( constructors.get(0), object); //'3.把上面的類再封裝為SingleGeneratedAdapterObserver適配器類,(內部有一個GeneratedAdapter)' return new SingleGeneratedAdapterObserver(generatedAdapter); } GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()]; //多個構造器 for (int i = 0; i < constructors.size(); i++) { //'4.生成多個GeneratedAdapter適配器類' adapters[i] = createGeneratedAdapter(constructors.get(i), object); } //'4. CompositeGeneratedAdaptersObserver類(內部有GeneratedAdapter隊列)' return new CompositeGeneratedAdaptersObserver(adapters); } //'5. ReflectiveGenericLifecycleObserver類' return new ReflectiveGenericLifecycleObserver(object); }
所以我們可以看到現在有下面圖片這些觀察者:

5.1 使用FullLifecycleObserver:
interface FullLifecycleObserver extends LifecycleObserver { void onCreate(LifecycleOwner owner); void onStart(LifecycleOwner owner); void onResume(LifecycleOwner owner); void onPause(LifecycleOwner owner); void onStop(LifecycleOwner owner); void onDestroy(LifecycleOwner owner); }
我們可以看到該接口不是public 類型,所以我們不能直接外部編寫實現類,但是我們可以引入: implementation "android.arch.lifecycle:common-java8:1.1.1"
這樣我們就可以使用DefaultLifecycleObserver
接口類:
public interface DefaultLifecycleObserver extends FullLifecycleObserver { }
我們可以看到是public
的。
DefaultLifecycleObserver observer = new DefaultLifecycleObserver() { @Override public void onCreate(@NonNull LifecycleOwner owner) { } @Override public void onStart(@NonNull LifecycleOwner owner) { } @Override public void onResume(@NonNull LifecycleOwner owner) { } @Override public void onPause(@NonNull LifecycleOwner owner) { } @Override public void onStop(@NonNull LifecycleOwner owner) { } @Override public void onDestroy(@NonNull LifecycleOwner owner) { } }; 複製代碼
同時回調的時候,通過FullLifecycleObserverAdapter
轉換器觀察者來回調:
class FullLifecycleObserverAdapter implements GenericLifecycleObserver { private final FullLifecycleObserver mObserver; FullLifecycleObserverAdapter(FullLifecycleObserver observer) { mObserver = observer; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { switch (event) { case ON_CREATE: mObserver.onCreate(source); break; case ON_START: mObserver.onStart(source); break; case ON_RESUME: mObserver.onResume(source); break; case ON_PAUSE: mObserver.onPause(source); break; case ON_STOP: mObserver.onStop(source); break; case ON_DESTROY: mObserver.onDestroy(source); break; case ON_ANY: throw new IllegalArgumentException("ON_ANY must not been send by anybody"); } } }
5.2 使用GenericLifecycleObserver:
public interface GenericLifecycleObserver extends LifecycleObserver { void onStateChanged(LifecycleOwner source, Lifecycle.Event event); }
我們可以直接使用:
class AObserver implements GenericLifecycleObserver{ @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { } }
我們可以看到都是AdapterObserver
調用onStateChanged
方法,然後間接調用我們寫的具體的Observer
的相關方法,而GenericLifecycleObserver
內部正好就是onStateChanged
,所以就不需要額外的AdapterObserver
適配器觀察者,所以就直接返回了該Observer
了。
5.3 使用普通的LifecycleObserver:
先說過搞笑的事情,就是很多文章都會說:
開頭說引入:引入annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
。
後面說Lifecycle 你寫了XXXLifecycleObserver後,編譯後會自動生成XXXLifeObserver_LifecycleAdapter文件。
然後我忘記引入了上面的引用,找這個輔助文件怎麼找都找不到,然後相關回調通知又都能順利成功回調,搞得我一臉懵逼,後面只能去看源碼,才知道了原因: 有引用,就會生成輔助文件,沒有引入就會自動通過反射調用相關方法,去調用回調。
5.3.1 (生成輔助文件)使用SingleGeneratedAdapterObserver/CompositeGeneratedAdaptersObserver:
public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver { private final GeneratedAdapter mGeneratedAdapter; SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) { mGeneratedAdapter = generatedAdapter; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { '//調用了GeneratedAdapter的callMethods方法' mGeneratedAdapter.callMethods(source, event, false, null); mGeneratedAdapter.callMethods(source, event, true, null); } }
這是我們自己寫的Observer類:
class DemoLifeObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void CCCC(LifecycleOwner owner) { } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void AAAA(LifecycleOwner owner) { } @OnLifecycleEvent(Lifecycle.Event.ON_START) public void DDDD(LifecycleOwner owner) { } @OnLifecycleEvent(Lifecycle.Event.ON_ANY) public void EEEE(LifecycleOwner owner,Lifecycle.Event event) { } }
我們生成的輔助文件(也就是GeneratedAdapter類):
public class DemoLifeObserver_LifecycleAdapter implements GeneratedAdapter { final DemoLifeObserver mReceiver; DemoLifeObserver_LifecycleAdapter(DemoLifeObserver receiver) { this.mReceiver = receiver; } //'調用了callMethods方法:' @Override public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) { boolean hasLogger = logger != null; if (onAny) { if (!hasLogger || logger.approveCall("EEEE", 4)) { '//調用了我們具體的觀察者的方法' mReceiver.EEEE(owner,event); } return; } if (event == Lifecycle.Event.ON_CREATE) { if (!hasLogger || logger.approveCall("CCCC", 2)) { '//調用了我們具體的觀察者的方法' mReceiver.CCCC(owner); } if (!hasLogger || logger.approveCall("AAAA", 2)) { '//調用了我們具體的觀察者的方法' mReceiver.AAAA(owner); } return; } if (event == Lifecycle.Event.ON_START) { if (!hasLogger || logger.approveCall("DDDD", 2)) { '//調用了我們具體的觀察者的方法' mReceiver.DDDD(owner); } return; } } }
5.3.2 (通過反射來調用)使用ReflectiveGenericLifecycleObserver:
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver { private final Object mWrapped; private final CallbackInfo mInfo; ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass()); } @Override public void onStateChanged(LifecycleOwner source, Event event) { mInfo.invokeCallbacks(source, event, mWrapped); } }
我們看見這個Observer自帶了onStateChanged方法,所以肯定不需要ObserverAdapter適配做中轉了,直接返回這個對象即可。
然後具體跟下去,我們來看mInfo.invokeCallbacks(source, event, mWrapped);
,無非就是根據註解的值,反射調用相應的代碼:
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) { invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target); invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,target); } private static void invokeMethodsForEvent(List<MethodReference> handlers, LifecycleOwner source, Lifecycle.Event event, Object mWrapped) { if (handlers != null) { for (int i = handlers.size() - 1; i >= 0; i--) { handlers.get(i).invokeCallback(source, event, mWrapped); } } } void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) { //noinspection TryWithIdenticalCatches try { switch (mCallType) { case CALL_TYPE_NO_ARG: mMethod.invoke(target); break; case CALL_TYPE_PROVIDER: mMethod.invoke(target, source); break; case CALL_TYPE_PROVIDER_WITH_EVENT: mMethod.invoke(target, source, event); break; } } catch (InvocationTargetException e) { throw new RuntimeException("Failed to call observer method", e.getCause()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
通過反射調用的參數我們也可以知道,我們的參數可以寫多個:
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void AAAA(LifecycleOwner owner) { } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void AAAA(LifecycleOwner source, Lifecycle.Event event) { } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void AAAA(LifecycleOwner source, Lifecycle.Event event, Object target) { //'這個Object target參數也就是你自己寫的並且通過addObserver傳入的Observer' }
結語:
該文章介紹了我們傳入不同的Observer後,內部是怎麼轉換處理,及最後的回調通知我們的上層。
PS:但是這裡我覺得有一點命名的誤區:
都是中間的適配器觀察者: SingleGeneratedAdapterObserver
, FullLifecycleObserverAdapter
,
大家看到沒有,FullLife
的居然叫ObserverAdapter
, 理論上我覺得應該是FullLifecycleAdapterObserver
,哈哈因為它也是一個觀察者。