preface

For Android development, we are certainly familiar with the Activity/Fragment lifecycle. Here is the official Activity lifecycle diagram:

Callbacks to component life cycle functions have a strict order in Android, which is the basis for normal development and presentation of data. It is controlled by the Android system and we cannot interfere with it.

So it’s normal to do some logical processing in an Activity/Fragment lifecycle function, but this is perfectly normal and has some drawbacks that we’ll look at step by step.

The body of the

defects

The defects here are minor, since we can’t intervene with the Activity lifecycle methods, but we generally have to write a lot of content to specific lifecycle methods, which leads to the problem of too much logical code in the lifecycle callback methods.

Lifecycle is Lifecycle. If I separate these callback functions and put them in a class, I will do what I need to do in that class’s callback during that Lifecycle.

Summary of Lifecycle

Lifecycle is the foundation for the JetPack component and various components of the subsequent MVVM architecture will need to be associated with this.

The source code comments

I personally feel that the first way to look at the source code is to look at its comments. Only by looking at the comments the author wrote for it is the most primitive and fastest way to understand the function of this class. Let’s look at the annotation for Lifecycle:

// Comment the first paragraph
* Defines an object that has an Android Lifecycle. {@link androidx.fragment.app.Fragment Fragment}
* and {@link androidx.fragment.app.FragmentActivity FragmentActivity} classes implement
* {@link LifecycleOwner} interface which has the {@link LifecycleOwner#getLifecycle()
* getLifecycle} method to access the Lifecycle. You can also implement {@link LifecycleOwner}
* in your own classes.
Copy the code

Lifecycle is an object that defines an Android Lifecycle. Such as fragments and FragmentActivities in AndroidX or your own custom classes that implement the LifecycleOwner interface and also implement the getLifecycle method to return Lifecycle objects.

Lifecycle needs to hold the life of the component, and the class that implements the LifecycleOwner interface is the Lifecycle holder.

// Comment on the second paragraph
<p>
* {@link Event#ON_CREATE}, {@link Event#ON_START}, {@link Event#ON_RESUME} events in this class
* are dispatched <b>after</b> the {@link LifecycleOwner}'s related method returns.
* {@link Event#ON_PAUSE}, {@link Event#ON_STOP}, {@link Event#ON_DESTROY} events in this class
* are dispatched <b>before</b> the {@link LifecycleOwner}'s related method is called. * For instance, {@link Event#ON_START} will be dispatched after * {@link android.app.Activity#onStart onStart} returns, {@link Event#ON_STOP} will be dispatched * before {@link android.app.Activity#onStop onStop} is called. * This gives you  certain guarantees on which state the owner isin.
* <p>
Copy the code

There is an important concept called Event, which corresponds to the Activity’s lifecycle method callbacks, but is slightly different, namely ON_CREATE, ON_START, and ON_RESUME are distributed after their associated lifecycle method callbacks. ON_PAUSE, ON_STOP, and ON_DESTROY are distributed before their associated lifecycle method callbacks.

Before looking at the source code, familiarize yourself with some of the common functions and uses of Lifecycle.

Basic Usage 1- Observe component lifecycle changes

You can add an observer to the lifecycle holder as follows:

/ / the Activity code
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Lifecycle is lifecycle and observers can be added to it
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            Logger.d("source = $source event = $event")}}}Copy the code

As you can see the observer pattern used here by adding an observer to Lifecycle and notifying the observer when Lifecycle’s Lifecycle changes is very simple and runs as follows:

Basic Usage 2- Gets and determines the lifecycle of the current component

Lifecycle will also be used to determine the state of the View. For example, LiveData has a feature that will not successfully add an observer when the Activity/Fragment Lifecycle is in a Destory.

/ / code LiveData
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
    assertMainThread("observe");
    // Do not add while the lifecycle holder is in a DESTROYED state
    if (owner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return;
    }
    / / to omit
}
Copy the code

From here we know that Lifecycle needs to save the Lifecycle state of the current component.

Lifecycle class source

Lifecycle source code is very sparse and from above we can get an idea of what will be inside Lifecycle by looking directly at the code:

/ / Lifecycle code
public abstract class Lifecycle {

    // Add an observer
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
    // Remove the observer
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);
    // Get the current component status
    @MainThread
    @NonNull
    public abstract State getCurrentState();
    // Lifecycle event inner class
    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY;
        // More on that later
        @Nullable
        public static Event downFrom(@NonNull State state) {
            switch (state) {
                case CREATED:
                    return ON_DESTROY;
                case STARTED:
                    return ON_STOP;
                case RESUMED:
                    return ON_PAUSE;
                default:
                    return null; }}// omit the method
    }
    // Life cycle state inner class
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0; }}}Copy the code

Lifecycle can be used by adding observers and notifying them of changes to component Lifecycle events, as well as saving and retrieving the current Lifecycle state.

Relationship between State and Event

The distinction here is that since an Event is an Event that occurs instantaneously, a State is required to hold the State of the current component.

However, State has fewer definitions than Event. That is to say, there is not one State after an Event occurs.

There is a perfect illustration of the relationship between the two on the official website, that is, both ON_CREATE and ON_STOP callback events are CREATED State, which explains why there are fewer enumerations of State. In this case, I get that the current State is CREATED. The Activity is just finished executing ON_CREATE or ON_STOP, with questions, we explore the source code.

conclusion

Lifecycle will be taken care of by Lifecycle and the next article will look at the steps that implement LifecycleOwner activities to take care of Lifecycle events.