jetpack之lifecycle的原理分析
我们之前知道了lifecycle的奇妙之处,那么lifecycle为什么会如此奇妙?💭
前置知识
没有看过lifecyce基础的可以看这篇文章:
jetpack之lifecycle的入门使用[特殊字符]https://blog.csdn.net/i_xiang_la_shi/article/details/147167228了解过上面的文章,我们就能够知道lifecycle中有几个类:LifecycleOwner和LifecycleObserver。
核心组件
其实这两个类就是lifecycle的两个核心组件,除了这两个,还有一个我们在使用的时候看不到的大能:LifecycleRegistry。
所以,构成lifecyc的核心组件有:LifecycleOwner、LifecycleObserver以及LifecycleRegistry。
LifecycleOwner——生命周期持有者
我们先看看熟悉的lifecycleowner的源码吧:
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
public val lifecycle: Lifecycle
}
上面的代码很简单,lifecycowner的接口的内容也很少,就只有一个lifecycle的对象。
实现了LifecycleOwner的类都是具有生命周期的例如AppcompatActivity以及Fragment。
在此就拿Fragment的源码做说明:
在如上的图片中我们可以看到Fragment实现了LifecycleOwner。这样,我们就能够为Fragment组件来添加观察者了。😋
LifecycleRegistry——生命周期的注册中心
先说一下它的作用:
- 管理
LifecycleOwner
的生命周期状态(如CREATED
、RESUMED
)。 - 维护观察者列表,并在状态变化时通知所有注册的
LifecycleObserver
它的重要程度可见一斑,我们来分析一下它的源码:
open class LifecycleRegistry private constructor(
provider: LifecycleOwner,
private val enforceMainThread: Boolean
) : Lifecycle() {
//...
}
我们可以看到,它实现了抽象类Lifecycle。其实在LifecycleOwner中的Licycle实例一般都是LifecycleRegistry。
那么他是如何管理LifecycleOwner的生命周期状态的?
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;
@MainThread
@Deprecated("Override [currentState].")
open fun markState(state: State) {
enforceMainThreadIfNeeded("markState")
currentState = state
}
在它的源码里面发现了markState的代码,在其中我们可以看到他有一个赋值方法,这小子藏着坏呢(〃>目<),其中的代码并不是直接将state这个状态赋值过去。
override var currentState: State
get() = state
/**
* Moves the Lifecycle to the given state and dispatches necessary events to the observers.
*
* @param state new state
*/
set(state) {
enforceMainThreadIfNeeded("setCurrentState")
moveToState(state)
}
我们可以看到它的赋值是进入了一个moveToState方法:,这里我就只需要知道,这个方法是进行了时间分发,和state的更新即可。
如何实现第二个作用的?
override fun addObserver(observer: LifecycleObserver) {
enforceMainThreadIfNeeded("addObserver")
val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
val statefulObserver = ObserverWithState(observer, initialState)
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
var targetState = calculateTargetState(observer)
addingObserverCounter++
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()
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer)
}
if (!isReentrance) {
// we do sync only on the top level.
sync()
}
addingObserverCounter--
}
这个方法相信大家都不陌生了。
它的作用就是LifecycleRegistry的第二个作用了——维护观察者列表,并在状态变化时通知所有注册的 LifecycleObserver。
LifecycleRegistry先解析到这里,接下来我们看LifecycleObserver:
LifecycleObserver——生命周期观察者
它的作用是:
监听生命周期事件(如 ON_CREATE
、ON_RESUME
),通过注解或接口实现回调
因为在上面的LifecycleRegitry中我们知道了只有注册了观察者我们才能够让lifecycle感知到此组件(指的是添加了观察者的组件)的生命周期变化,这里,我就不贴源码了。😋
运作流程
1. 观察者注册
- 通过
lifecycle.addObserver()
注册观察者。 LifecycleRegistry
内部维护ObserverWithState
列表,封装观察者及其当前状态。
2. 事件分发
- 当
Activity
生命周期方法(如onCreate()
)被调用时,LifecycleRegistry
通过handleLifecycleEvent()
更新状态并遍历观察者列表,调用其对应的回调方法。
- 线程安全:强制在主线程执行状态更新(enforceMainThreadIfNeeded方法),避免并发问题。
3. 状态同步
- 新注册的观察者会立即收到当前状态的同步事件(如注册时
Activity
已处于RESUMED
状态,则触发ON_CREATE
→ON_START
→ON_RESUME
回调)。