跳至主要內容

Android Lifecycle机制探究

PPLong大约 14 分钟学习AndroidAndroid Jetpack

Android Lifecycle机制探究

前言

为学习Android Jetpack组件,了解ViewModel、LiveData原理,Lifecycle是绕不开的一环

Lifecyle

LifecycleObserver

引入:在控制Activity生命周期时,常常会在onStop或者onResume中写很多开关控制语句,防止内存泄漏等,不好维护;同时onStart有耗时任务,则onStop结束后而耗时任务还没完成,导致内存泄漏

目的:用于构建生命周期感知型组件的类和接口.生命周期感知型组件可执行操作来响应另一个组件(如 activity 和 fragment)的生命周期状态的变化

特点:采用观察者模式

核心组件

  • LifecycleOwner:被观察者, Activity与Fragment
  • LifecycleObserber: 观察者,自己业务组件需要继承该类
  • Lifecycle:存储有关组件的生命周期状态信息

基本概念

State与Event

Lifecycle Event-States关系图
Lifecycle Event-States关系图

State

  • DESTROYED: 不会再分发事件
  • INITIALIZED: 刚创建时
  • CREATED: 已创建
  • STARTED
  • RESUMED
public enum class State {
    /**
     * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
     * any more events. For instance, for an [android.app.Activity], this state is reached
     * **right before** Activity's [onDestroy][android.app.Activity.onDestroy] call.
     */
    DESTROYED,

    /**
     * Initialized state for a LifecycleOwner. For an [android.app.Activity], this is
     * the state when it is constructed but has not received
     * [onCreate][android.app.Activity.onCreate] yet.
     */
    INITIALIZED,

    /**
     * Created state for a LifecycleOwner. For an [android.app.Activity], this state
     * is reached in two cases:
     *
     *  * after [onCreate][android.app.Activity.onCreate] call;
     *  * **right before** [onStop][android.app.Activity.onStop] call.
     *
     */
    CREATED,

    /**
     * Started state for a LifecycleOwner. For an [android.app.Activity], this state
     * is reached in two cases:
     *
     *  * after [onStart][android.app.Activity.onStart] call;
     *  * **right before** [onPause][android.app.Activity.onPause] call.
     *
     */
    STARTED,

    /**
     * Resumed state for a LifecycleOwner. For an [android.app.Activity], this state
     * is reached after [onResume][android.app.Activity.onResume] is called.
     */
    RESUMED;

    /**
     * Compares if this State is greater or equal to the given `state`.
     *
     * @param state State to compare with
     * @return true if this State is greater or equal to the given `state`
     */
    public fun isAtLeast(state: State): Boolean {
        return compareTo(state) >= 0
    }
}

Event

  • ON_CREATE
  • ON_START
  • ON_RESUME
  • ON_PAUSE
  • ON_STOP
  • ON_DESTORY
  • ON_ANY: 匹配任何的事件

Core

LifecyleOwner

被观察者,指向持有Lifecycle的对象

public interface LifecycleOwner {
    public val lifecycle: Lifecycle
}

LifecycleObserver

观察者,自己业务组件需要继承该类

public interface LifecycleObserver

Lifecycle

具有生命周期的类的实际实现类

public abstract class Lifecycle {
  @MainThread
  public abstract fun addObserver(observer: LifecycleObserver)

  @MainThread
  public abstract fun removeObserver(observer: LifecycleObserver)

  // 当前对象生命状态
  @get:MainThread
  public abstract val currentState: State
}

LifecycleRegistry

Lifecycle的具体实现类,能够处理状态变化时对多个Observer的通知

open class LifecycleRegistry private constructor(
    provider: LifecycleOwner,
    private val enforceMainThread: Boolean
) : Lifecycle() {
  
    constructor(provider: LifecycleOwner) : this(provider, true)
  
    init {
      lifecycleOwner = WeakReference(provider)
    }
  	
    // 维系Observer的Map
    private var observerMap = FastSafeIterableMap<LifecycleObserver, ObserverWithState>()
  	// 当前状态
  	private var state: State = State.INITIALIZED
    
   /**
   * The provider that owns this Lifecycle.
   * Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak
   * the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,
   * because it keeps strong references on all other listeners, so you'll leak all of them as
   * well.
   */
    private val lifecycleOwner: WeakReference<LifecycleOwner>
}

简单使用

自定义Observer类继承DefaultLifecycleObserver接口,并重写onResume等默认方法,并在Activity onCreate时,通过lifeCycle.addObserver添加响应Observer即可。一个Activity可以add多个Observer

Android26以后 Activity中默认持有lifeCycle对象,实例为LifeCycleRegistry,自动持有LifecycleOwner的弱引用。且实现了LifecycleOwner接口,已返回lifecycle对象

原理探究

Native如何实现Lifecycle?

Native如何接入Lifecycle?

在AppCompatActivity - FragmentActvity - ComponentActivity 中实现了 LifecycleOwner 接口,并持有lifeCycleRegistry对象,直接进行了初始化

// ComponentActivity
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
		// 将生命周期事件传递给ReportFragment
    ReportFragment.injectIfNeededIn(this);
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}

// ReportFragment
public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
      	// 核心方法,但此处先不看这里
        // On API 29+, we can register for the correct Lifecycle callbacks directly
        LifecycleCallbacks.registerIn(activity);
    }
    // Prior to API 29 and to maintain compatibility with older versions of
    // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
    // need to support activities that don't extend from FragmentActivity from support lib),
    // use a framework fragment to get the correct timing of Lifecycle events
  	// 将该Fragment通过FragmetnManager添加到Activity中
    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();
    }
}

因此处理Lifecycle回调的核心类应该是ReportFragment, 那SDK < 29时,什么时候进行回调呢,猜测应该是在Fragment的生命周期中有相关回调

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

private void dispatch(@NonNull Lifecycle.Event event) {
  	// 如果SDK小于29 则自己进行dispatch,如果大于29,则通过之前的mActivityLifecycleCallbacks进行回调
    if (Build.VERSION.SDK_INT < 29) {
        // Only dispatch events from ReportFragment on API levels prior
        // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
        // added in ReportFragment.injectIfNeededIn
        dispatch(getActivity(), event);
    }
}


static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
  	// 殊途同归,根据Activity实现接口类型不同最终还是调用到LifecycleRegistry的handleLifecycleEvent方法
  	// Deprecated
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

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

// LifecycleRegistry
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent");
    moveToState(event.getTargetState());
}

private fun moveToState(next: State) {
    if (state == next) {
        return
    }
    check(!(state == State.INITIALIZED && next == State.DESTROYED)) {
        "no event down from $state in component ${lifecycleOwner.get()}"
    }
    state = next
    if (handlingEvent || addingObserverCounter != 0) {
        newEventOccurred = true
        // we will figure out what to do on upper level.
        return
    }
  	// 设置字段表明正在处理并分发事件
    handlingEvent = true
    sync()
    handlingEvent = false
    if (state == State.DESTROYED) {
        observerMap = FastSafeIterableMap()
    }
}

// 进行状态变更通知
private fun sync() {
    val lifecycleOwner = lifecycleOwner.get()
        ?: throw IllegalStateException(
            "LifecycleOwner of this LifecycleRegistry is already " +
                "garbage collected. It is too late to change lifecycle state."
        )
    while (!isSynced) {
        newEventOccurred = false
        if (state < observerMap.eldest()!!.value.state) {
            backwardPass(lifecycleOwner)
        }
        val newest = observerMap.newest()
        if (!newEventOccurred && newest != null && state > newest.value.state) {
            forwardPass(lifecycleOwner)
        }
    }
    newEventOccurred = false
}

// 若最早加入Map的Observer与最晚加入Map的Observer状态一致, 且与当前状态一致,则认为是同步的
private val isSynced: Boolean
  get() {
      if (observerMap.size() == 0) {
          return true
      }
      val eldestObserverState = observerMap.eldest()!!.value.state
      val newestObserverState = observerMap.newest()!!.value.state
      return eldestObserverState == newestObserverState && state == newestObserverState
}

先搁置一下这里的sync方法,当SDK >= 29时,生命周期响应又走哪条路线?

@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

// ReportFragment
public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
      	// 核心方法
        // On API 29+, we can register for the correct Lifecycle callbacks directly
        LifecycleCallbacks.registerIn(activity);
    }
}

@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

  static void registerIn(Activity activity) {
      activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
  }

  @Override
  public void onActivityCreated(@NonNull Activity activity,
          @Nullable Bundle bundle) {
  }

  @Override
  public void onActivityPostCreated(@NonNull Activity activity,
          @Nullable Bundle savedInstanceState) {
      // 核心:dispatch对应的Lifecycle Event
      dispatch(activity, Lifecycle.Event.ON_CREATE);
  }

  @Override
  public void onActivityStarted(@NonNull Activity activity) {
  }

  @Override
  public void onActivityPostStarted(@NonNull Activity activity) {
      dispatch(activity, Lifecycle.Event.ON_START);
  }

}
// ReportFragment
companion onbject {
    @JvmStatic
    internal fun dispatch(activity: Activity, event: Lifecycle.Event) {
        if (activity is LifecycleRegistryOwner) {
            activity.lifecycle.handleLifecycleEvent(event)
            return
        }
        if (activity is LifecycleOwner) {
            val lifecycle = (activity as LifecycleOwner).lifecycle
            if (lifecycle is LifecycleRegistry) {
                lifecycle.handleLifecycleEvent(event)
            }
        }
    }
}


// Activity
// 添加callback到Activity的mActivityLifecycleCallbacks的集合中
public void registerActivityLifecycleCallbacks(
        @NonNull Application.ActivityLifecycleCallbacks callback) {
  synchronized (mActivityLifecycleCallbacks) {
      mActivityLifecycleCallbacks.add(callback);
}

// Activity(注意不是ComponentActivity, 可能是Android新版本中使用了该监听方式,Lifecycle就直接用原生的监听,而不再使用ComponentActivity中使用ReportFragment生命周期的回调方式)
// 何时进行回调?猜测应该在Activity的生命周期中
@CallSuper
protected void onStart() {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
    mCalled = true;
    mFragments.doLoaderStart();
  	// 核心
    dispatchActivityStarted();
    getAutofillClientController().onActivityStarted();
}
  
private void dispatchActivityStarted() {
    getApplication().dispatchActivityStarted(this);
  	// 获取ActvityLifecycleCallback总和
    Object[] callbacks = collectActivityLifecycleCallbacks();
    if (callbacks != null) {
        for (int i = 0; i < callbacks.length; i++) {
            ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityStarted(this);
        }
    }
}

private Object[] collectActivityLifecycleCallbacks() {
  Object[] callbacks = null;
  // 此处就用到了上文我们所说的mActivityLifecycleCallbacks集合
  synchronized (mActivityLifecycleCallbacks) {
      if (mActivityLifecycleCallbacks.size() > 0) {
          callbacks = mActivityLifecycleCallbacks.toArray();
      }
  }
  return callbacks;
}

总结一下:

  • SDK < 29: 通过ReportFragment的生命周期调用dispatch方法,经过LifecycleRegistry ObserverWithStat LifecycleEventObserver.onStateChanged进行回调
  • SDK >= 29: 通过Activity的生命周期进行回调,经过mActivityLifecycleCallbacks 与 LifecycleCallbacks,最终还是进入到ReportFragment的dispatch方法中,其余步骤与之前相同

理解State与Event的转换关系

Lifecycle Event-States关系图
Lifecycle Event-States关系图

Lifecycle中对状态与事件的运用不复杂,但需要梳理清上述的逻辑关系,还是需要这张图。

先看一下如下的方法,并理解其与图上的顺序关系

// State
// 由高状态向低状态顺序进发时触发的事件
public fun downFrom(state: State): Event? {
    return when (state) {
        State.CREATED -> ON_DESTROY
        State.STARTED -> ON_STOP
        State.RESUMED -> ON_PAUSE
        else -> null
    }
}
// 由低状态向高状态回退时触发的事件
public fun downTo(state: State): Event? {
    return when (state) {
        State.DESTROYED -> ON_DESTROY
        State.CREATED -> ON_STOP
        State.STARTED -> ON_PAUSE
        else -> null
    }
}

// 由低状态向高状态顺序进发时触发的事件
public fun upFrom(state: State): Event? {
    return when (state) {
        State.INITIALIZED -> ON_CREATE
        State.CREATED -> ON_START
        State.STARTED -> ON_RESUME
        else -> null
    }
}

// 由高状态向低状态回退时触发的事件
public fun upTo(state: State): Event? {
    return when (state) {
        State.CREATED -> ON_CREATE
        State.STARTED -> ON_START
        State.RESUMED -> ON_RESUME
        else -> null
    }
}

// Event
// 返回触发指定事件后的下一个State
public val targetState: State
    get() {
        when (this) {
            ON_CREATE, ON_STOP -> return State.CREATED
            ON_START, ON_PAUSE -> return State.STARTED
            ON_RESUME -> return State.RESUMED
            ON_DESTROY -> return State.DESTROYED
            ON_ANY -> {}
        }
        throw IllegalArgumentException("$this has no target state")
    }

forward与backward

回到之前的sync函数,现在开始关注与具体状态转换、事件分发密切相关的backwardPass与forwardPass方法

// 进行状态变更通知
private fun sync() {
    val lifecycleOwner = lifecycleOwner.get()
        ?: throw IllegalStateException(
            "LifecycleOwner of this LifecycleRegistry is already " +
                "garbage collected. It is too late to change lifecycle state."
        )
    while (!isSynced) {
        newEventOccurred = false
        if (state < observerMap.eldest()!!.value.state) {
            backwardPass(lifecycleOwner)
        }
        val newest = observerMap.newest()
        if (!newEventOccurred && newest != null && state > newest.value.state) {
            forwardPass(lifecycleOwner)
        }
    }
    newEventOccurred = false
}

private fun backwardPass(lifecycleOwner: LifecycleOwner) {
  	// 获得由新到久添加的Observer排列的Iterator
    val descendingIterator = observerMap.descendingIterator()
    while (descendingIterator.hasNext() && !newEventOccurred) {
        val (key, observer) = descendingIterator.next()
      	// 当observer的状态超过当前lifecycle状态时,需要将Observer的状态进行回退,并触发状态回退时的一系列事件
        while (observer.state > state && !newEventOccurred && observerMap.contains(key)
        ) {
          	// 获取顺序进发到下一个状态需要触发到事件
            val event = Event.downFrom(observer.state)
                ?: throw IllegalStateException("no event down from ${observer.state}")
          	// 暂时不了解
            pushParentState(event.targetState)
          	// observer调用dispatchEvent(一般为业务方法)
            observer.dispatchEvent(lifecycleOwner, event)
            popParentState()
        }
    }
}
// 与backwardPass相反
private fun forwardPass(lifecycleOwner: LifecycleOwner) {
    // 获得由久到新添加的Observer排列的Iterator
    val ascendingIterator: Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> =
        observerMap.iteratorWithAdditions()
    while (ascendingIterator.hasNext() && !newEventOccurred) {
        val (key, observer) = ascendingIterator.next()
        // 当observer的状态落后于当前lifecycle状态时,需要将Observer的状态进行前进,并触发状态前进后时的一系列事件
        while (observer.state < state && !newEventOccurred && observerMap.contains(key)
        ) {
            pushParentState(observer.state)
            // 获取顺序进发到下一个状态需要触发到事件
            val event = Event.upFrom(observer.state)
                ?: throw IllegalStateException("no event up from ${observer.state}")
            observer.dispatchEvent(lifecycleOwner, event)
            popParentState()
        }
    }
}

// 这里的Observer实际为ObserverWithState(后续有讲到)
fun dispatchEvent(owner: LifecycleOwner?, event: Event) {
  	// 更新当前observer状态
    val newState = event.targetState
  	// 采用最小的state(为什么?)
    state = min(state, newState)
  	// 这里才是真正Observer的执行处
    lifecycleObserver.onStateChanged(owner!!, event)
    state = newState
}

总结一下:

  • Backward: state < observer.state, 此时由新到久为每个Observer分发Event
  • Forward: state > observer.state, 此时由久到新为每个Observer分发Event

为什么此处需要push/pop ParentState?

先别急,先看一下Lifecycle是如何添加Observer的

添加Observer

我们知道Observer是处理具体的业务逻辑的
以ViewModel为例,在ComponentActivity初始化时添加了对应的LifecycleObserver来处理ViewModel的生命周期【关于ViewModel的生命周期在之前的文章有相关探究】

// ComponentActivity
getLifecycle().addObserver(new LifecycleEventObserver() {
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source,
            @NonNull Lifecycle.Event event) {
      	// 业务逻辑
        if (event == Lifecycle.Event.ON_DESTROY) {
            // Clear out the available context
            mContextAwareHelper.clearAvailableContext();
            // And clear the ViewModelStore
            if (!isChangingConfigurations()) {
                getViewModelStore().clear();
            }
        }
    }
});

Lifecycle(此处为LifecycleRegistry) 如何添加一个Observer呢?

// LifecyleRegistry
override fun addObserver(observer: LifecycleObserver) {
    enforceMainThreadIfNeeded("addObserver")
  	// state状态设置
    val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
  	// 包装Observer与State
    val statefulObserver = ObserverWithState(observer, initialState)
  	// 若已存在该Observer, 则不再添加
    val previous = observerMap.putIfAbsent(observer, statefulObserver)
    if (previous != null) {
        return
    }
    val lifecycleOwner = lifecycleOwner.get()
        ?: // it is null we should be destroyed. Fallback quickly
        return
    val isReentrance = addingObserverCounter != 0 || handlingEvent
  	// 计算应该跳转到的state
    var targetState = calculateTargetState(observer)
  	
    addingObserverCounter++
  	// 根据targetState使该observer进行dispatchEvent(同步)
    while (statefulObserver.state < targetState && observerMap.contains(observer)
    ) {
        pushParentState(statefulObserver.state)
        val event = Event.upFrom(statefulObserver.state)
            ?: throw IllegalStateException("no event up from ${statefulObserver.state}")
        statefulObserver.dispatchEvent(lifecycleOwner, event)
        popParentState()
      	// 需要重新计算targetState
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer)
    }
  	// 仅当最顶层调用时才同步(性能优化?)
    if (!isReentrance) {
        // we do sync only on the top level.
        sync()
    }
    addingObserverCounter--
}
// LifecycleRegistry
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    enforceMainThreadIfNeeded("addObserver");
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
  	// 将自己写的observer包装为一个ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
}


static class ObserverWithState {
  State mState;
  LifecycleEventObserver mLifecycleObserver;

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

// Lifecycling
// 判断observer的类型并创建对应的Adapter
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);
    }
  	// 自定义的lifecycleobserver是基于DefaultLifecycleObserver,而其又是FullLifecycleObserver的派生类,因此这里往往会构造FullLifecycleObserverAdapter
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }
  	// ...
}

// LifecycleObserver.ObserverWithState
void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = event.getTargetState();
    mState = min(mState, newState);
  	// 关键方法
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}

粘性事件

粘性事件

Android Lifecycle 在对Observer分发事件采取的是粘性分发机制,即一个在Lifecycle处于任一State,新添加一个Observer时状态并不会直接跳到该State,而是从INITIALIZE按序经历多个事件一步步走到指定state。

理解Lifecycle到粘性事件机制有助于理解LiveData的粘性事件,因此先来了解一下Lifecycle粘性事件的原理

原理

当lifecycle添加observer时,会通过calculateTargetState方法计算出当前observer应该跳转到的暂时的最终状态,并且将该observer状态一步步前进到指定的targetState,并分发相应事件。这里是临时的是因为每次observer回调相关事件时可能会对当前observer、其他observer或lifecycle产生改变,导致targetState产生改变,因此需要重新计算。

// LifecyleRegistry
override fun addObserver(observer: LifecycleObserver) {
 		// ...
    val isReentrance = addingObserverCounter != 0 || handlingEvent
  	// 计算应该跳转到的state
    var targetState = calculateTargetState(observer)
  	
    addingObserverCounter++
  	// 核心: 根据targetState使该observer进行dispatchEvent(同步)
    while (statefulObserver.state < targetState && observerMap.contains(observer)
    ) {
        pushParentState(statefulObserver.state)
        val event = Event.upFrom(statefulObserver.state)
            ?: throw IllegalStateException("no event up from ${statefulObserver.state}")
        statefulObserver.dispatchEvent(lifecycleOwner, event)
        popParentState()
      	// 需要重新计算targetState
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer)
    }
  	// 仅当最顶层调用时才同步(性能优化?)
    if (!isReentrance) {
        // we do sync only on the top level.
        sync()
    }
    addingObserverCounter--
}

看完这段代码,会有两个疑问

  1. 为什么在进行observer进行事件响应前需要push该observer的state
  2. 如何进行targetState计算的?

这里将以上两个问题一并解答

targetState计算
// LifecycleRegistry
private fun calculateTargetState(observer: LifecycleObserver): State {
    val map = observerMap.ceil(observer)
    val siblingState = map?.value?.state
    val parentState =
        if (parentStates.isNotEmpty()) parentStates[parentStates.size - 1] else null
    return min(min(state, siblingState), parentState)
}

// FastSafeIterableMap
// 根据key获取上一个添加到这个map中的元素
@Nullable
public Map.Entry<K, V> ceil(K k) {
    if (contains(k)) {
        return mHashMap.get(k).mPrevious;
    }
    return null;
}

FastSafeIterableMap

一个线程不安全的HashMap, 同时支持Iterable遍历,基于添加顺序进行迭遍历

calculateTargetState逻辑:对比三者的状态,取最小值。

  • 当前lifecycle的state
  • 当前元素的上一个元素(兄弟元素)的state
  • parentState栈顶元素的state

那为什么一定需要这三个元素才能计算出targetState呢?

  1. 为什么需要当前lifecycle的state?

不用说,lifecycle的state是核心条件。

  1. 为什么需要当前元素的上一个元素的stat?

考虑以下情况:

操作步骤:在Lifecycle生命周期为RESUMED时,添加一个ObserverA,在A的接收的事件为ON_CREATE时,为该lifecycle添加一个observerB,并观察此时Log。

override fun onResume() {
    super.onResume()
  	// 确保lifecycle的状态此时为RESUMED(原理为Activity onResume执行步骤)
  	// super.onResume()后其生命周期并非立马就为RESUMED
    lifecycleScope.launch {
        delay(2000)
        lifecycle.addObserver(MPLifecycleObserver())
    }
}

class MPLifecycleObserver : LifecycleEventObserver {
    private val TAG = javaClass.name
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        Log.d(
            TAG,
            "MPLifecycleObserver onStateChanged: source status: ${source.lifecycle.currentState}, event: ${event.name}"
        )
        if (event.targetState == Lifecycle.State.CREATED) {
            Log.d(TAG, "MPLifecycleObserver add KPLifecycleObserver")
            source.lifecycle.addObserver(KPLifecycleObserver())
        }
    }
}

class KPLifecycleObserver : LifecycleEventObserver {
    private val TAG = javaClass.name
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        Log.d(
            TAG,
            "KPLifecycleObserver onStateChanged: source status: ${source.lifecycle.currentState}, event: ${event.name}"
        )
    }
}

相关Log:

// Log
MPLifecycleObserver onStateChanged: source status: RESUMED, event: ON_CREATE
MPLifecycleObserver add KPLifecycleObserver
MPLifecycleObserver onStateChanged: source status: RESUMED, event: ON_START
MPLifecycleObserver onStateChanged: source status: RESUMED, event: ON_RESUME
KPLifecycleObserver onStateChanged: source status: RESUMED, event: ON_CREATE
KPLifecycleObserver onStateChanged: source status: RESUMED, event: ON_START
KPLifecycleObserver onStateChanged: source status: RESUMED, event: ON_RESUME

先回顾之前forward与backward的顺序,在状态从小到大进发时,是按照Observer添加先后顺序进行通知的,而在状态由大到小进发时,通知的顺序是Observer添加顺序逆序进行的,这也符合观察先来后到的顺序。(A先于B观察,则A便要慢于B结束观察)

如果没有parentState与siblingState,根据addObserver while循环的逻辑,calculateTargetState计算出的state为lifecycle的state,此时ObserveB将一步一步不停歇地走到lifecycle的state,即为RESUMED,但此时observerA的接收的状态为INITIALIZED ,后添加的Observer就比先添加的Observer的状态更靠后了,这是不符合上述提到的Observer事件接收的顺序的。因此需要维护一个sibling的Observer来维护其state,来保证后添加的observer的state在添加时状态一定小于先添加的Observer

  1. 为什么需要parentState这个栈结构?为什么要在通知Observer前进行状态的push与pop?

核心

Lifecycle机制核心是通过Activity中回调机制,借助依附Activity中的ReportFragment的生命周期来完成具体回调机制

参考资料 🔗