Android Jetpack component learning (1): LifeCycle

foreword

Lifecycle is a component launched by Google to deal with issues related to the life cycle of Activity and Fragment. It is a structure of observer mode.

Using lifeCycle can establish a monitoring relationship between the owner and the observer of the life cycle. When the life cycle of the owner changes, the observer can monitor it in time and make corresponding processing. At the same time, the observer can judge the current state very conveniently. What is the lifetime of the owner.

From the above description, it is obvious that the usage scenario of LifeCycle is the business logic related to the life cycle of Activity and Fragment.

For example, in the MVP structure, the Presenter needs to be aware of the life cycle of the Activity or Fragment, so that it can process the business logic related to the life cycle in a timely manner. Under this requirement, we can use LifeCycle to observe the life cycle and make timely decisions. deal with.

1. Use

LifeCycle is mainly divided into two parts: LifeCycleOwner and LifeCycleObserver.

1. LifeCycleOwner

LifeCycleOwner, the owner of the life cycle, generally refers to Activity and Fragment, and the customization limit is very large, so we will not discuss it this time.

Both AppCompatActivity and Fragment in V4 have implemented the LifeCycleOwner interface by default, so we can use it directly in development.

2. LifeCycleObserver

LifeCycleObserver, life cycle observers need to implement this interface.
There is no method in this interface. The observation of the life cycle is realized by annotating onLifecycleEvent . The sample code is as follows:

class SingleMainLifeCycle : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onActivityOnCreate() {

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onActivityOnResume() {

    }
}

In this way, we create a LifeCycleObserver instance, and then we can connect the observer with the owner, and then we can monitor. The sample code is as follows:

class SingleMainActivity : BaseActivity<ActivitySingleMainBinding>() {

    override var viewBinding: ActivitySingleMainBinding = ActivitySingleMainBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //绑定lifecycle观察者
        lifecycle.addObserver(SingleMainLifeCycle())
    }
}

In the above code, since the LifeCycleOwner interface has been implemented in the Activity, you can directly use getLifeCycle()the method to obtain the lifecycle for binding. After binding, the method in SingleMainLifeCycle will be executed in the corresponding life cycle.

3. Determine the state reached by the life cycle execution

Lifecycle can judge whether the current life cycle has reached a certain state, that is, whether it is greater than or equal to the current state. The code is as follows:

        if(lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)){

        }

2. Source code summary analysis

The following is an overview of the source code. Taking Fragment as an example, getLifeCycle()the method of viewing Fragment can be seen as follows:

    @Override
    @NonNull
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

It is the implemented LifeCycleOwnerinterface, mLifecycleRegistry respectively performStart(), performResumeand other perform methods are called

mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.**);

Check out this method, as follows:

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

is sync()synchronized to other observers by method execution,

    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                    + "garbage collected. It is too late to change lifecycle state.");
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

There are two methods in this method backwardPass()and forwardPass()it is to execute the synchronization process. Taking it backwardPass()as an example, it will mObserverMaptraverse, execute dispatchEvent(), and synchronize the state to all Observers.

    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

Instead,mObserverMap it is used for storage LifecycleObserver, and listeners will be added to this data structure when the bound method is called.

Summarize

LifeCycle adopts the observer mode to monitor the life cycle of the LifeCycleOwner, and the observer can take corresponding actions in a timely manner.
As a relatively independent component in jetpack, LifeCycle has many advantages of its own; at the same time, it is the basic content of other components, such as the lifecycle of LiveData and ViewModel, which also depends on the Lifecycle framework.

Guess you like

Origin blog.csdn.net/cat_is_so_cute/article/details/121230103