The way Lifecycle is used

Custom LifecycleObserver

// 1. Customize LifecycleObserver
class MLifecycleObserver : LifecycleObserver {

    // 2. Call the corresponding method in the lifecycle you want to observe
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun loadData(a){}@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun cleanData(a){}}// 3. Register the observer and observe the changes of the host life cycle
class MFragment : Fragment() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        
        val mLifecycleObserver = MLifecycleObserver()
        lifecycle.addObserver(mLifecycleObserver)
    }
}

Copy the code

LifecycleEventObserver

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


class MLifecycleEventObserver : LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        // TODO receives all lifecycle processes and takes what it wants TODO
        when (event) {
            Lifecycle.Event.ON_RESUME -> {
            }
            Lifecycle.Event.ON_DESTROY -> {
            }
        }
    }
}




Copy the code

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); } class MLifecycleEventObserver : FullLifecycleObserver { override fun onCreate(owner: LifecycleOwner?) { TODO("Not yet implemented") } override fun onDestroy(owner: LifecycleOwner?) { TODO("Not yet implemented") } }Copy the code

Some basic concepts

  • LifecycleOwner interface (Lifecycle holder) : Implement the getLifecycle method of this interface and return a Lifecycle object for external use. Add an observer via LifecycleObserve (LifecycleObserve)

  • LifecycleObserver interface (LifecycleObserver) : Implement this interface, register with the LifecycleOwner host, and observe the Lifecycle events of the host.

  • Lifecycle(objects aware of the Lifecycle) : Hosts that implement the LifecycleOwner interface need to internally generate a Lifecycle for use by the outside world

  • Lifecycle State: INITIALIZED, CREATED, STARTED, RESUMED, DESTROYED

  • Event(host lifecycle method counterpart) : Regarded as an Event corresponding to the host lifecycle

  • Simple diagram

How can fragments and activities use Lifecycle

Fragment

Here only posted the key part, specific can look at their own source

First, the Fragment inherits LifecycleOwner, so the Fragment is a host object, its Lifecycle is LifecycleRegistry, and handleLifecycleEvent is used to send the corresponding Lifecycle event

So fragments simply call Lifecycle methods to distribute events within the corresponding Lifecycle process

public class Fragment implements LifecycleOwner { mLifecycleRegistry = new LifecycleRegistry(this); @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } void performCreate(Bundle savedInstanceState) { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); } void performStart() { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); } // TODO calls performXXX for each lifecycle. // mLifecycleRegistry allocates the corresponding event. Void performXXX(){ mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.XXX); }}Copy the code

Activity

With a simple understanding of fragments that use Lifecycle, do you think that activities are the same? Distribute events throughout the lifecycle?

Like fragments, LifecycleRegistry is used, so distributing a lifecycle event is also a handleLifecycleEvent

public class ComponentActivity implements LifecycleOwner { private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }}Copy the code

But searching for handleLifecycleEvent doesn’t find a place to use the activity,

I wanted to call handleLifecycleEvent, which would have to get LifecycleRegistry, so I searched the Activity’s getLifecycle() and finally found the ReportFragment

Finally, I found the relationship between them in ComponentActivity

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
    
}
Copy the code

So looking at the ReportFragment, you can see that it adds an empty Fragment to the Activity

public static void injectIfNeededIn(Activity activity) { android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); manager.executePendingTransactions(); }}Copy the code

Call Dispatch in each lifecycle and pass in events

@Override
public void onResume() {
    super.onResume();
    dispatch(Lifecycle.Event.ON_RESUME);
}

@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}

@Override
public void onDestroy() {
    super.onDestroy();
    dispatch(Lifecycle.Event.ON_DESTROY);
}
Copy the code

This will eventually get called here, and that will get activity.getlifecycle (), which will distribute the handleLifecycleEvent

static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) { if (activity instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; }}Copy the code

The analysis of the LifecycleRegistry

Relationship between state and Event

To better understand the relationship between State and Event, use a graph first

Using a drawing THAT I saved before, but I don’t know where I saved it from

AddObserver, process for registering an observer

We know that by calling addObserver to register the observer, we can receive the full life cycle events of the host, so let’s just start with this method and see what it does for us

Note: it is complete, that is, the onCreate and onStart methods before the onResume method are accepted, but the ondeStory method is not distributed.

Let’s look at the code for the while loop

Note: statefulObserver is the observer we passed in, but wrapped

While ((statefulObserver.mState.com pareTo (targetState) < 0 && mObserverMap. The contains (observer))) {/ / TODO call wrapper class distribution of events statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); // TODO calculates the current targetState again targetState = calculateTargetState(observer); }Copy the code

Suppose we register an observer with the onResume method. In this case, the target state is RESUME

We can see that using statefulObserver is currently in the INITIALIZED state

Compared to the target state, is behind, is less than the target state, so the while statement will enter

Enters after see statefulObserver. DispatchEvent () variable upEvent,

With the State State, you get oneEvent#ON_CREATE

Enter the method dispatchEvent of our Observer wrapper class

It uses the getStateAfter method to get the state it needs to progress to, using the Event Event passed in

Finally, the onStateChanged method is called to send the event

HandleLifecycleEvent The process of the host life cycle

We know from the previous analysis that in lifecycle methods, handleLifecycleEvent is called to distribute events

Public void handleLifecycleEvent(@nonnull Lifecycle.Event Event) { State next = getStateAfter(event) as above; // This method will eventually call sync() moveToState(next); }Copy the code

MoveToState (Next) this method will eventually call sync(), so sync()

The isSynced() method determines whether the state of all observers in the mObserverMap is synchronized to the state of the host

The host state < observer state goes to backwardPass, as in foreground to background

The process inside is similar to the previous analysis, but withDownEventIs the process of life cycle retrogression

The second if condition, which determines the size of the state of the host and observer, goes to forwardPass for host state > observer state

This is a life-cycle progression process, so useUpEvent

The system handles three unused LifecycleObservers

The three LifecycleObserver methods are different, but the dispatchEvent will call onStateChanged to lifecycleEventObserver

Remember that in addObserver, we wrapped our passed observer as ObserverWithState

Here we do a processing of the observer we passed inlifecycleEventObservermethods

So go into the Life Cleevening Server method and take a look

You can see that adapters are created for different types of observers

Here is a look at the FullLifecycleObserverAdapter directly

As you can see, he inherits lifecycleEventObserver and overrides onStateChanged, so the dispatchEvent call will come in here and then call the method we implemented

Why does adding an annotation to a custom LifecycleObserver method allow the method to be called at the corresponding lifecycle event

As you can see from above, there are two types of Adapter for custom LifecycleObserver processing. Why

Look at the ReflectiveGenericLifecycleObserver

It calls the methods of your custom LifecycleObserver via reflection

Then look at CompositeGeneratedAdaptersObserver

If you refer to kapt androidx. Lifecycle: lifecycle – compiler: 2.0.0 ‘annotation processor, the annotation processor will help you generate the corresponding class, Then CompositeGeneratedAdaptersObserver call the corresponding method