阅读 573

虐面试官系列Lifecycle篇 - (4)源码分析之响应的观察者们

前言:

原谅我标题党😑😑

Lifecycle系列:

虐面试官系列Lifecycle 篇 -(1)基础讲解

虐面试官系列Lifecycle篇 - (2)源码分析之 Event & State

虐面试官系列Lifecycle篇 - (3)源码分析之注册 & 发送

虐面试官系列Lifecycle篇 - (4)源码分析之响应

待完成:

虐面试官系列Lifecycle 篇 - (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,哈哈因为它也是一个观察者。

文章分类
Android
文章标签