Lifecycle component usage scenarios

LifecycleOwner is currently available on AppCompatActivity and Fragment for vendors to know the life cycle of a View.

  public class AppCompatActivity extends FragmentActivity  { xx}
  public class FragmentActivity extends ComponentActivity { xx} 
  public class ComponentActivity extends Activity implements LifecycleOwner {xx}
  
  public class Fragment implements  LifecycleOwner{xx}
Copy the code

Lifecycle component use

Since AppCompatActivity and Fragment are LifecycleOwner, we don’t need to deal with that. A subscriber is our Presenter, and what a subscriber does is

Mark yourself as a subscriber

     public class MyPresenter implements LifecycleObserver {xxx}
Copy the code

2. Add annotations to events of interest

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        public void onMyCreate(a) {
            Log.e(TAG, "onCreate: " + "oncreate");
       }
Copy the code

Lifecycle component overview

Use of two design patterns: observer design pattern Decorator design pattern

Observed :LifecycleOwner

  • Responsibilities:
      1. Managing subscribers, how do you manage them, of course, by adding add and removing remove, very much like collections, right, observers must have collections.
      1. Distribute events
      private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
      public abstract void addObserver(@NonNull LifecycleObserver observer);
      public abstract void removeObserver(@NonNull LifecycleObserver observer);
      public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    Copy the code

The subscriber: LifecycleObserver

  • Responsibilities: Add comments to events of interest.

Why decorator mode?

  • Decorator pattern purpose: Method enhancement

    • First: When adding subscribers, encapsulate the original Obsever as ObserverWithState so that a State variable can be added to handle the State. The GenericLifecycleObserver object is encapsulated again because there are two ways to handle event distribution: a. Pure reflex (ReflectiveGenericLifecycleObserver) b.a pt. (such as CompositeGeneratedAdaptersObserver multiple similar class), can be called onStateChanged method.
    • Second, apt generates new classes that also encapsulate Observer objects.

LifePhaseRegistry is a class where the viewer performs duties —- that actually work

The subscriber management code has no special features, distribution operations can be seen. See AppCompatActivity and Fragment respectively.

  • AppCompatActivity is embedded with a ReportFragment object, and the ReportFragment life cycle is bound to AppCompatActivity so that it can be called synchronally.
 public static void injectIfNeededIn(Activity activity) {
    // ProcessLifecycleOwner should always correctly work and some activities may not extend
    // FragmentActivity from support lib, so we use framework fragments for activities
    android.app.FragmentManager manager = activity.getFragmentManager();
    if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        // Hopefully, we are the first to make a transaction.manager.executePendingTransactions(); }}Copy the code

Glide senses the life cycle of the host Activity and adds a Fragment to the host. You can do the same for perception.

public class ReportFragment extends Fragment {
    @Override
    public void onStart(a) {
        super.onStart(); . dispatch(Lifecycle.Event.ON_START); }private void dispatch(Lifecycle.Event event) {...if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceofLifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); }}}}Copy the code
  • Fragment system developers directly modified the Fragment source code to add LifecycleRegistry distribution events.
    public class Fragment implementsLifecycleOwner {
     LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
       @Override
     public Lifecycle getLifecycle(a) {
         return mLifecycleRegistry;
     }
    
    void performStart(a) {... onStart(); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); . }... }Copy the code

Events received by subscribers

Subscribers can get a complete chain of events, such as: If you add a subscriber to MainAct’s onStart method, it will still receive the onCreate event, because when addObserver, The subscriber starts in the INITIALIZED state and then when it receives an onStart event, it sends an event step by step from onCreate to create its state value.

  public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
   // For example, if the onStart event is launched, the current state can be calculated as STARTED
   // Then the state of the subscribers in the set is still INITIALIZED, so step by step to +, to reach the same state
      State next = getStateAfter(event);
      moveToState(next);
  }
@Override
  public void addObserver(@NonNull LifecycleObserver observer) {
      State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
      ObserverWithState statefulObserver = newObserverWithState(observer, initialState); . State targetState = calculateTargetState(observer);while ((statefulObserver.mState.compareTo(targetState) < 0&& mObserverMap.contains(observer))) { statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));  targetState = calculateTargetState(observer); }... }static State getStateAfter(Event event) {
      switch (event) {
          case ON_CREATE:
          case ON_STOP:
              return CREATED;
          case ON_START:
          case ON_PAUSE:
              returnSTARTED; . }private static Event upEvent(State state) {
      switch (state) {
          case INITIALIZED:
          case DESTROYED:
              return ON_CREATE;
          case CREATED:
              returnON_START; . }Copy the code

Lifecycle component’s handling of annotations

Lifecycle components can be read first and then you can simply implement two ways to handle annotations yourself. If not, check out the LifeCycele component.

  • Pure reflection has no technical barriers

  • Apt technology

    • 1. Because classes are handled by Elements at compile time, some basic Element knowledge is required.

      Java-apt implementation of Element details

    • 2. Androidx engineering seems not support ‘com. Google. Auto. Services: auto – service: 1.0 rc4’ only honestly new resource folder to specify the path of the annotation processor.

    • 3. The annotation processor library may not be found in As, you will need to look at the source code for LifeCycle.

AnnotationDemo, a simple annotation implementation