Preface:

Forgive me for the clickbait 😑😑

Lifecycle series:

Lifecycle — (1) The basics

Lifecycle – (2) Source code analysis of Event & State

Lifecycle – (3) Source code analysis registration & send

Lifecycle – (4) Response to source code analysis

Pending:

Lifecycle – (5) Integrate Lifecycle in several ways with the source code differences

It’s been a long time since I wrote this article, but I recently decided to write about another basic piece of Android: the official Android architecture component series. Lifecycle is going to be written down, so this series will be about Lifecycle.


Body:

In Lifecyele we can see that: finally, callback notifications are made by real observer method calls:

mLifecycleObserver.onStateChanged(owner, event);
Copy the code

But when we use it in general, it looks like this:

class LifeObserver implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void CCCC(LifecycleOwner owner) {
        
    }
}
Copy the code

There is no onStateChanged method, so why?

In fact, the mLifecycleObserver is not an Observer we pass in, but an intermediate adapter Observer that receives the notification and then internally calls our own Observer to send the notification.

Simple is ObserverWithState. DispatchEvent — — > contains onStateChanged (the owner, Event) method AdapterObserver(if the Observer we pass contains onStateChanged method, such as GenericLifecycleObserver, There is no adapter Observer in the middle) — > specify the Observer we wrote

As we said earlier, our observer object is encapsulated by the addObserver method and added to the ObserverWithState object:

static class ObserverWithState {

    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
    
        '// We can see that our incoming Observer is converted to another Observer(or adapter) by getCallback :mLifecycleObserver'
        mLifecycleObserver = Lifecycling.getCallback(observer);
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        '// You can see the last callback is to call onStateChanged method of mLifecycleObserver 'mLifecycleObserver.onStateChanged(owner, event); mState = newState; }}Copy the code

Let’s take a look at what our Observer is converted to:


@NonNull
static GenericLifecycleObserver getCallback(Object object) {

    //'1. FullLifecycleObserver observer, and at the same time return FullLifecycleObserverAdapter adapter class'
    if (object instanceof FullLifecycleObserver) {
        returnnew FullLifecycleObserverAdapter((FullLifecycleObserver) object); } / /'2. GenericLifecycleObserver and return the class directly '
    if (object instanceof GenericLifecycleObserver) {
        return(GenericLifecycleObserver) object; } final Class<? > klass = object.getClass(); //'pass the Observer through getObserverConstructorType method is introduced to determine, whether to have the corresponding generated helper classes'
    int type = getObserverConstructorType(klass);
    
    //'If there is a corresponding generated helper class'
    if (type == GENERATED_CALLBACK) {
        List<Constructor<? extends GeneratedAdapter>> constructors =
                sClassToAdapters.get(klass);
                
        //'There's only one constructor'
        if (constructors.size() == 1) {
            
            //'GeneratedAdapter Adapter class'
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
                    
            //'3. The top of the class to encapsulate for SingleGeneratedAdapterObserver adapter class, (internal have a GeneratedAdapter)'    
            returnnew SingleGeneratedAdapterObserver(generatedAdapter); } GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()]; // Multiple constructorsfor (int i = 0; i < constructors.size(); i++) {
            //'4. Generate multiple GeneratedAdapter adapter classes'adapters[i] = createGeneratedAdapter(constructors.get(i), object); } / /'4. CompositeGeneratedAdaptersObserver class (internal GeneratedAdapter queue)' 
        returnnew CompositeGeneratedAdaptersObserver(adapters); } / /'5. ReflectiveGenericLifecycleObserver class' 
    return new ReflectiveGenericLifecycleObserver(object);
}
Copy the code

So we can see that we now have the following picture of these observers:

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

Copy the code

We can see that the interface is not a public type, so we can’t direct external implementation class to write, but we can introduce: implementation “android. Arch. Lifecycle: common – java8:1.1.1”

Then we can use the DefaultLifecycleObserver interface class:

public interface DefaultLifecycleObserver extends FullLifecycleObserver {

}
Copy the code

We can see it’s 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) {

    }
};
Copy the code

At the same time the callback, back and forth through FullLifecycleObserverAdapter converter observer adjustment:

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"); }}}Copy the code

5.2 use GenericLifecycleObserver:

public interface GenericLifecycleObserver extends LifecycleObserver {

    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
    
}
Copy the code

We can just use:

class AObserver implements GenericLifecycleObserver{

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        
    }
}
Copy the code

We can see that the AdapterObserver calls onStateChanged and then indirectly calls the specific Observer related methods that we wrote, The GenericLifecycleObserver happens to be onStateChanged inside, so no additional AdapterObserver AdapterObserver is required, so it is returned directly to the Observer.

5.3 Using the regular LifecycleObserver:

The funny thing is that a lot of articles say:

Beginning said introduction: introducing annotationProcessor “android. Arch. Lifecycle: the compiler: 1.1.1”.

Lifecycle after you write XXXLifecycleObserver, XXXLifeObserver_LifecycleAdapter will be generated automatically when compiled.

And then I forget the introduction of the above reference, find the supporting documents how to find all can not find, then relevant correction notice can be successful correction, make me a face of meng, behind only to see the source code, don’t know the reason: there are references to supporting documentation is generated, no introduction will automatically call the method through reflection, the callback to call.

5.3.1 (generate auxiliary files) using 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) {
        '// callMethods method of GeneratedAdapter is called '
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null); }}Copy the code

Here is our own Observer class:

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) {

    }
}
Copy the code

The auxiliary file we generated (that is, the GeneratedAdapter class) :

public class DemoLifeObserver_LifecycleAdapter implements GeneratedAdapter { final DemoLifeObserver mReceiver; DemoLifeObserver_LifecycleAdapter(DemoLifeObserver receiver) { this.mReceiver = receiver; } / /'callMethods are called:'@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)) {
        '// calls our specific observer's method '
        mReceiver.EEEE(owner,event);
      }
      return;
    }
    if (event == Lifecycle.Event.ON_CREATE) {
      if(! hasLogger || logger.approveCall("CCCC", 2)) {
      '// calls our specific observer's method '
        mReceiver.CCCC(owner);
      }
      if(! hasLogger || logger.approveCall("AAAA", 2)) {
      '// calls our specific observer's method '
        mReceiver.AAAA(owner);
      }
      return;
    }
    if (event == Lifecycle.Event.ON_START) {
      if(! hasLogger || logger.approveCall("DDDD", 2)) {
      '// calls our specific observer's method '
        mReceiver.DDDD(owner);
      }
      return; }}}Copy the code

5.3.2 (call) via the reflection using 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); }}Copy the code

We can see that the Observer comes with the onStateChanged method, so we definitely don’t need the ObserverAdapter adapter for the transit, just return this object.

InvokeCallbacks (source, event, mWrapped); Reflection calls the corresponding code based on the value of the annotation:

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); }}Copy the code

We can also see from reflection that we can write multiple arguments:


@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) {
        //'The Object target argument is the Observer that you wrote yourself and passed in via addObserver'
}
Copy the code

Conclusion:

This article describes how the internal conversion process is handled when we pass in different observers, and how the final callback notifies our upper level.

PS: But here I think there is a mistake in naming:

Is in the middle of the adapter observer: SingleGeneratedAdapterObserver, FullLifecycleObserverAdapter,

You see no, FullLife had called ObserverAdapter, in theory, I think should be FullLifecycleAdapterObserver, haha because it is also an observer.