Android Jetpack - Lifecycle 组件使用及解析

Lifecycle 简介

Lifecycle 是一个可以感知宿主生命周期变化的组件。常见的宿主包括 Activity/Fragment、Service 和 Application。Lifecycle 会持有宿主的生命周期状态的信息,当宿主生命周期发生变化时,会通知监听宿主的观察者。

  • Lifecycle 可以有效的避免内存泄漏和解决 android 生命周期的常见难题
  • Livecycle 是一个表示 android 生命周期及状态的对象

Lifecycle 基本使用

Jetpack 为我们提供了两个接口:

  • 被观察者: LifecycleOwner 用于连接有生命周期的对象,如activity,fragment
  • 观察者: LifecycleObserver 用于观察查 LifecycleOwner

被监听的系统组件需要去实现 LifecycleOwner 接口,观察者需要实现 LifecycleObserver 接口。

Lifecycle 框架使用观察者模式实现观察者监听被观察者的生命周期的变化。

1、定义被观察者

通过实现 LifecycleOwner 接口

如上图:我们使用 activity 不需要再自己写实现接口的代码

2、定义观察者

通过实现LifecycleObserver接口

public class BasePresenter implements LifecycleObserver {

  WeakReference mWeakReference;

  /**
   * 绑定view
   */
  public void attachView(T view) {
    mWeakReference = new WeakReference<>(view);
  }

  /**
   * 解绑
   */
  public void detachView() {
    if (mWeakReference != null) {
      mWeakReference.clear();
      mWeakReference = null;
    }
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
  void onCreateX(LifecycleOwner owner) {

  }

  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  void onStartX(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  void onStop(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
  void onResume(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
  void onPause(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
  void onDestory(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
  void onAny(LifecycleOwner owner) {
  }
}

通过注解在观察者类中定义需要监听的生命周期

注:以下方法都会在被观察者生命周期变化时调用

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
  void onCreateX(LifecycleOwner owner) {

  }

  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  void onStartX(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  void onStop(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
  void onResume(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
  void onPause(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
  void onDestory(LifecycleOwner owner) {
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
  void onAny(LifecycleOwner owner) {
  }
3、完成订阅关系

在activity中使用 被观察者.addObserver(观察者)

getLifecycle().addObserver(presenter);

具体使用代码如下:

public class GoodsPresenter extends BasePresenter {

  IGoodsModel iGoodsModel = new GoodsModel();

  /**
   * 执行业务逻辑
   */
  public void fetch() {
    if (mWeakReference != null && iGoodsModel != null) {
      iGoodsModel.loadGoodsData(new IGoodsModel.OnLoadListener() {
        @Override
        public void onComplete(List goods) {
          ((IGoodsView) mWeakReference.get()).showGoodsView(goods);
        }

        @Override
        public void onError(String msg) {

        }
      });
    }
  }

  @Override
  void onCreateX(LifecycleOwner owner) {
    super.onCreateX(owner);
    Log.i("wuc", "create");
  }

  @Override
  void onDestory(LifecycleOwner owner) {
    super.onDestory(owner);
    Log.i("wuc", "destroy");
  }

}
public abstract class BaseActivity, V extends IBaseView> extends AppCompatActivity {

  protected T mPresenter;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPresenter = createPresenter();
    mPresenter.attachView((V) this);
    init();
  }

  protected void init() {

  }

  protected abstract T createPresenter();

  @Override protected void onDestroy() {
    super.onDestroy();
    mPresenter.detachView();
  }
}
public class MainActivity extends BaseActivity, IGoodsView> implements IGoodsView {

  ListView listView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = findViewById(R.id.listView);
    mPresenter.fetch();
  }

  @Override
  protected GoodsPresenter createPresenter() {
    return new GoodsPresenter();
  }

  @Override public void showGoodsView(List goods) {
    listView.setAdapter(new GoodsAdapter(this, goods));
  }

  @Override public void showErrorMessage(String msg) {

  }

  @Override protected void init() {
    super.init();
    getLifecycle().addObserver(mPresenter);
  }
}

核心原理

Lifecycle

Lifecycle 内部仅包含一个全局变量,三个抽象方法、两个枚举类。

Lifecycle 包含的三个抽象函数,分别用于添加 LifecycleObserver 、移除 LifecycleObserver、获取当前 Lifecycle 所处的状态值。代码如下所示:

@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);

@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);

@MainThread
@NonNull
public abstract State getCurrentState();

Lifecycle 内部包含的两个枚举类,用于标记 Activity/Fragment 等具有生命周期状态的事物当前所处的状态

Event 类用于抽象 Activity/Fragment 的生命周期事件发生变化时所触发的事件。例如,当 Activity 的每个生命周期事件回调函数(onCreate、onStart 等)被触发时都会被抽象为相应的 ON_CREATE、ON_START 两个 Event。

public enum Event {
    ON_CREATE,
    ON_START,
    ON_RESUME,
    ON_PAUSE,
    ON_STOP,
    ON_DESTROY,
    ON_ANY
}

State 类用于标记 Lifecycle 的当前生命周期状态。

public enum State {
    // 当处于 DESTROYED 状态时,Lifecycle 将不会发布其它 Event 值
    // 当 Activity 即将回调 onDestory 时则处于此状态
    DESTROYED,
    // 已初始化的状态。例如,当 Activity 的构造函数已完成,但还未回调 onCreate 时则处于此状态
    INITIALIZED,
    CREATED,
    STARTED,
    RESUMED;
    // 如果当前状态大于入参值 state 时,则返回 true
    public boolean isAtLeast(@NonNull State state) {
        return compareTo(state) >= 0;
    }
}

具体的 Event 和 State 之间的转换关系,可以参照下图:

构成 Android Activity 生命周期的状态和事件
Lifecycle 相关的接口
1. LifecycleOwner

LifecycleOwner 接口用于标记其实现类具备 Lifecycle 对象。我们日常使用的 androidx.appcompat.app.AppCompatActivity 和 androidx.fragment.app.Fragment 均实现了该接口。

@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    @NonNull
    Lifecycle getLifecycle();
}
2. LifecycleObserver

LifecycleObserver 是一个空接口,大部分情况下真正具有使用意义的是它的子接口 ,LifecycleObserver 可以说仅是用于类型标记

@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {

}

LifecycleEventObserver 用于监听 Lifecycle 的生命周期变化,可以获取到生命周期事件发生的具体变化

public interface LifecycleEventObserver extends LifecycleObserver {
    // 当 LifecycleOwner 对象的生命周期事件发生变化时将回调此方法
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

FullLifecycleObserver 根据 Activity/Fragment 这两个类的生命周期回调函数扩展了几个同名的抽象方法,可以看成是对 LifecycleEventObserver 进行更加具体的事件拆分

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);
}
3. OnLifecycleEvent

OnLifecycleEvent 是一个自定义注解,当开发者想要通过注解的形式来对应不同的生命周期回调时就需要使用到。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}

ReportFragment

根据 Activity 的生命周期状态的变化来管理我们的业务逻辑的话,那么可以很方便的使用类似如下代码来监听其生命周期状态的变化。

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        lifecycle.addObserver(object : 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()
                }
            }
        })
    }

那么 LifecycleEventObserver 是如何取得各个生命周期状态变化的事件(Lifecycle.Event)呢?或者说,是谁回调了 LifecycleEventObserveronStateChanged 方法呢?

在日常开发中,多数情况下我们使用的 Activity 都是继承于 androidx.appcompat.appcompat:xxx这个包内的 AppCompatActivity,而 AppCompatActivity 最终是会继承于 androidx.core.app.ComponentActivity, ComponentActivity 的 onCreate 函数是这样的:

    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }

通过 ReportFragment 使得 LifecycleEventObserver 可以接收到 Activity 所有的的 Lifecycle.Event。

injectIfNeededIn() 函数是一个静态函数,以 android.app.Activity 对象作为入参参数

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

ReportFragment 的 injectIfNeededIn() 函数会通过向 Activity 添加一个无 UI 界面的 Fragment(即 ReportFragment),间接获得 Activity 的各个生命周期事件的回调通知。ReportFragment 的生命周期函数都调用了dispatch()方法。

由于 ReportFragment 是挂载在 Activity 身上的,ReportFragment 本身的生命周期函数和所在的 Activity 是相关联的,通过在 ReportFragment 相应的生命周期函数里调用 dispatch(Lifecycle.Event.ON_XXXX) 函数发送相应的 Event 值,以此来间接获得 Activity 的各个生命周期事件的回调通知。

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

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

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

    @Override
    public void onStop() {
        super.onStop();
        dispatch(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

dispatch()方法则会判断 Activity 是否实现了 LifecycleOwner 接口,如果实现了该接口就调用 LifecycleRegisterhandleLifecycleEvent() 这样生命周期的状态就会借由 LifecycleRegistry 通知给各个 LifecycleObserver 从而调用其中对应 Lifecycle.Event 的方法。这种通过 Fragment 来感知 Activity 生命周期的方法其实在 Glide 的中也是有体现的。

private void dispatch(Lifecycle.Event event) {
    Activity activity = getActivity();
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}

@Deprecated
public interface LifecycleRegistryOwner extends LifecycleOwner {
    @NonNull
    @Override
    LifecycleRegistry getLifecycle();
}

handleLifecycleEvent方法中,State next = getStateAfter(event);
事件发生的时候,先得到当前 activity 应该出现的下一个状态。

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

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

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 newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
            // 正推
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

图表分析如下:

构成 Android Activity 生命周期的状态和事件
private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
            popParentState();
        }
    }
}

forwardPass(lifecycleOwner)方法中的细节 ObserverWithState observer = entry.getValue();找到 ObserverWithState 类调用 mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); 生成观察者适配器

static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

接下来就是调用 onStateChanged() 来通知 实现了 LifecycleObserver的类,生命周期发生了变化。

Lifecycling.lifecycleEventObserver(observer)

    @NonNull
    static LifecycleEventObserver lifecycleEventObserver(Object object) {
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }

        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }
        .......
        return new ReflectiveGenericLifecycleObserver(object);
    }
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}

ReflectiveGenericLifecycleObserver 的构造方法中就把 presenter 中的方法和注解保存了下来再通过 onStateChanged() 进行生命周期的方法的调用

这样,ReportFragment 就通过上述逻辑向外部转发了 Activity 发生的 Event 值。

LifecycleRegistry

ReportFragment 最终在向外传出 Lifecycle.Event 值时,调用的都是 LifecycleRegistry 对象的 handleLifecycleEvent(Lifecycle.Event)方法, Event 值拿到后, LifecycleRegistry 是如何将 Event 值转发给 LifecycleObserver 的?

LifecycleRegistry 屏蔽了生命周期持有类(Activity / Fragment 等)的具体类型,使得外部(Activity / Fragment 等)可以只负责转发生命周期事件,由LifecycleRegistry 来实现具体的事件回调和状态管理。androidx.activity.ComponentActivityandroidx.fragment.app.Fragment 都使用到了 LifecycleRegistry

 public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
            
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
            
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }   
}

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner {
            
    LifecycleRegistry mLifecycleRegistry;
           
    @Override
    @NonNull
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }      
}

LifecycleRegistry 的定位、作用和必须具备的功能

  • 不单单是 Activity 和 Fragment 可以实现 LifecycleOwner 接口,像 Service、Dialog 等具有生命周期的类一样可以实现 LifecycleOwner 接口,而不管 LifecycleOwner 的实现类是什么,其本身所需要实现的功能/逻辑都是一样的:addObserver、removeObserver、getCurrentState、遍历循环 observers 进行 Event 通知等。所以 Google 官方势必需要提供一个通用的 Lifecycle 实现类,以此来简化开发者实现 LifecycleOwner 接口的成本,最终的实现类即 LifecycleRegistry
  • LifecycleRegistry 需要持有 LifecycleOwner 对象来判断是否可以向其回调事件通知,但为了避免内存泄漏也不能直接强引用 LifecycleOwner,而是用 WeakReference mLifecycleOwner;
  • 当 Activity 处于 State.STARTED 状态时向其添加了一个 LifecycleEventObserver ,此时就必须向 LifecycleEventObserver 同步当前的最新状态值,所以 LifecycleEventObserver 就会先后收到 Lifecycle.Event.ON_CREATE、Lifecycle.Event.ON_START 两个 Event
  • LifecycleRegistry 向 Observer 发布 Event 值的触发条件有两种:
    • 新添加了一个 Observer,需要向其同步 Activity 当前的 State 值。在同步的过程中新的 Event 值可能刚好又来了,此时需要考虑如何向所有 Observer 同步最新的 Event 值
    • Activity 的生命周期状态发生了变化,需要向 Observer 同步最新的 State 值。在同步的过程中可能又添加了新的 Observer 或者移除了 Observer ,此时一样需要考虑如何向所有 Observer 同步最新的 Event 值

LifecycleRegistry 是 Lifecycle 的子类,其构造函数需要传入 LifecycleOwner 对象。

public class LifecycleRegistry extends Lifecycle {

    //一般一个 LifecycleRegistry 对应一个 LifecycleOwner 对象(Activity/Fragment等)
    //mState 就用来标记 LifecycleOwner 对象所处的当前生命周期状态
    private State mState;

    //持有对 LifecycleOwner 的弱引用,避免内存泄露
    private final WeakReference mLifecycleOwner;

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }
   
}

addObserver()函数的主要逻辑是:将传入的 observer 对象包装为 ObserverWithState 类型,方便将注解形式的LifecycleObserver(Java 7)和接口实现的 LifecycleObserver(Java 8)进行状态回调时的入口统一为 dispatchEvent() 方法。此外,由于当添加 LifecycleObserver 时 Lifecycle 可能已经处于非 INITIALIZED 状态了,所以需要通过循环检查的方式来向 ObserverWithState 逐步下发 Event 值。

    //Lifecycle 类中对 addObserver 方法添加了 @MainThread 注解,意思是该方法只能用于主线程调用
    //所以此处不需要考虑多线程的情况
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            //如果 observer 之前已经传进来过了,则不重复添加,直接返回
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            //如果 LifecycleOwner 对象已经被回收了,则直接返回
            return;
        }

        //如果 isReentrance 为 true,则说明此时以下两种情况至少有一个成立:
        //1. mAddingObserverCounter != 0。会出现这种情况,是由于开发者先添加了一个 LifecycleObserver ,当还在向其回调事件的过程中,在回调函数里又再次调用了 addObserver 方法添加了一个新的 LifecycleObserver
        //2.mHandlingEvent 为 true。即此时正处于向外回调 Lifecycle.Event 的状态
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;

        State targetState = calculateTargetState(observer);

        //递增加一,标记当前正处于向新添加的 LifecycleObserver 回调 Event 值的过程
        mAddingObserverCounter++;

        //statefulObserver.mState.compareTo(targetState) < 0 成立的话说明 State 值还没遍历到目标状态
        //mObserverMap.contains(observer) 成立的话说明 observer 还没有并移除
        //因为有可能在遍历过程中开发者主动在回调函数里将 observer 给移除掉了,所以这里每次循环都检查下
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            //将 observer 已经遍历到的当前的状态值 mState 保存下来
            pushParentState(statefulObserver.mState);
            //向 observer 回调进入“statefulObserver.mState”前需要收到的 Event 值
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            //移除 mState
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }

Lifecycle 的整个事件流程走向如下图:

https://juejin.cn/post/6847902220755992589#heading-14

你可能感兴趣的:(Android Jetpack - Lifecycle 组件使用及解析)