• Lifecycle (I) origins of Android Jetpack architectural components
  • Lifecycle (ii) for Android Jetpack architecture components
  • Lifecycle (iii) of Android Jetpack architectural components

Lifecycle using

Lifecycle(I) in the origin of the last article will give you a simple insight into this through an example:

Writing life-cycle dependent code directly into an Activity or Fragment leads to poorly organized code and error proliferation.

Lifecycle can move component-dependent code from Lifecycle methods into the component itself. That is, the lifecycle of an Activity or Fragment can be sensed within the component

This article will expand on the use of Lifecycle

Preliminary knowledge

Events and states within Lifecycle

Lifecycle corresponds to the Lifecycle of an Android view component with two enumerated types: Event and State:

    / / event
    public enum Event {
            ON_CREATE,
            ON_START,
            ON_RESUME,
            ON_PAUSE,
            ON_STOP,
            ON_DESTROY,
            ON_ANY
        }
    / / state
    /**
     * Lifecycle states. You can consider the states as the nodes in a graph and
     * {@link Event}s as the edges between these nodes.
     */
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0; }}Copy the code

The official notes tell us

You can think of States as points on a graph, and events as edges connecting those points on the graph.

Which is this picture:As for where the arrows and states come from, you can find the answer in LifecycleRegister:

static State getStateAfter(Event event) {
        switch (event) {
            case ON_CREATE:
            case ON_STOP:
                return CREATED;
            case ON_START:
            case ON_PAUSE:
                return STARTED;
            case ON_RESUME:
                return RESUMED;
            case ON_DESTROY:
                return DESTROYED;
            case ON_ANY:
                break;
        }
        throw new IllegalArgumentException("Unexpected event value " + event);
    }
Copy the code

DownEvent (State State) upEvent(State State) also illustrates the relationship in the figure above. If you are interested, you can view the source code yourself

  • Each Event maps to one of the Activity or Fragmnet lifecycle callbacks
  • Each State reflects the current State of the component tracked by Lifecycle

⚠️ Don’t think of Lifecycle as magical. It is essentially a simple observer pattern. First register the observer in the view controller, and the Android source code will distribute the Lifecycle events as the Lifecycle changes. Call onStateChan in LifecycleEventObserver by LifecycleRegister (LifecycleEventObserver) Ged method. This will be done in Lifecycle Iii

LifecycleOwner

public interface LifecycleOwner {
    
    @NonNull
    Lifecycle getLifecycle(a);
}
Copy the code

A single-method interface, as the name suggests: the class that implements this interface can be understood as a component with Lifecycle. It’s easy to imagine that activities and Fragments already implement this interface:

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner.ViewModelStoreOwner.Copy the code
public class Fragment implements 
		LifecycleOwner.ViewModelStoreOwner.Copy the code

So when Lifecycle is used you can call the interface method getLifecycle() directly in your Activity or Fragment

lifecycle.addObserver(NetStateManager)
Copy the code

Add observer

In addition, Lifecycle can also be customized by implementing LifecycleOwner, a custom LifeOwner will be implemented at the end of the Lifecycle series to help you understand

LifecycleObserver

The first step in using Lifecycle is to implement a LifecycleObserver:

object ContentPlayer : LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun prepare(context: Context) {
        // The player is ready
    }
    
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun unAttach(a) {
        // Release the currently held Activity resource
    }
    
    // Start playing
    fun Play(content: String){... }... }Copy the code

Method annotations explicitly specify when the method is called. In the example above, if you add a ContentPlayer observer to the Acitivity, the perpare() method is called when the Activity is created and unAttach() is called when the Activity is destroyed.

This is not the only way to implement LifecycleObserver. There are several built-in implementations for us to choose from: for example, LifecycleEventObservser has been built into the LifecycleObserver


object ContentPlayer : LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> TODO()
            Lifecycle.Event.ON_START -> TODO()
            Lifecycle.Event.ON_RESUME -> TODO()
            Lifecycle.Event.ON_PAUSE -> TODO()
            Lifecycle.Event.ON_STOP -> TODO()
            Lifecycle.Event.ON_DESTROY -> TODO()
            Lifecycle.Event.ON_ANY -> TODO()
        }
    }
}
Copy the code

Each time the state of the view controller changes, the event is called back to onStateChanged(), implementing the desired logic in the different event branches.

In fact, using the first method of using annotations, at runtime the LifecycleRegister class converts LifecycleObserver to LifecycleEventObservser via reflection or apt, so in some cases to avoid reflection consumption, LifecycleEventObservser can be a priority

Add observer

The last step only needs to be done in the Activity’s onCreated method:

override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        ...
        lifecycle.addObserver(ContentPlayer)
    }
Copy the code

One final consideration: if an ON_CREATE event is observed in Observser, and we only register the observer in the Activity’s onResume, will we still receive the ON_CREATE event that occurred before onResume()?

object Observer : LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(context: Context) {
        
        Log.d(TAG, "Observe onCreate event")}@OnLifecycleEvent(Lifecycle.Event.ON_Start)
    fun onStart(context: Context) {
        
        Log.d(TAG, "Observe onStart event")}... }Copy the code

The observer is then registered in the Activity’s onResume

override fun onResume(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        ...
        lifecycle.addObserver(Observser)
    }
Copy the code

The answer is: yes. So you can rest assured to use