認(rèn)識 Lifecycle
Lifecycle 是什么
Lifecycle
是 Jetpack
組件庫中的一個(gè)生命周期感知型組件。在 Lifecycle 出現(xiàn)之前肠套,需要手動從外部宿主(如 Activity根竿、Fragment 或自定義宿主)中將生命周期事件分發(fā)到功能組件內(nèi)部陵像,這勢必會造成宿主代碼復(fù)雜度增加。有了 Lifecycle 的存在犀填,搭建依賴于生命周期變化的業(yè)務(wù)邏輯變得簡單高效蠢壹,可以用一種統(tǒng)一的方式來監(jiān)聽 Activity、Fragment九巡、甚至是 Process 的生命周期變化,且大大減少了業(yè)務(wù)代碼發(fā)生內(nèi)存泄漏的風(fēng)險(xiǎn)。
事件和狀態(tài)
Lifecycle 中定義了7種生命周期事件:
- ON_CREATE: 對應(yīng)onCreate方法
- ON_START: 對應(yīng)onStart方法
- ON_RESUME: 對應(yīng)onResume方法
- ON_PAUSE: 對應(yīng)onPause方法
- ON_STOP: 對應(yīng)onStop方法
- ON_DESTROY: 對應(yīng)onDestroy方法
- ON_ANY: 匹配任何事件
和 5 種生命周期狀態(tài):
-
INITIALIZED: Lifecycle 初始化完成,且還未收到
onCreate()
事件時(shí)的狀態(tài)宋雏。 -
CREATED: 在
onCreate()
調(diào)用之后爸舒,或者onStop()
調(diào)用之后的狀態(tài)。 -
STARTED: 在
onStart()
調(diào)用之后湘今,或者onPause()
調(diào)用之后的狀態(tài)。 -
RESUMED: 在
onResume()
調(diào)用之后,onPause()
調(diào)用之前的狀態(tài)睬辐。 -
DESTROYED: 在
onDestory()
調(diào)用之后的狀態(tài)。
事件和狀態(tài)之間的關(guān)系如下圖所示宾肺,這也是 Lifecycle 分發(fā)生命周期狀態(tài)的流程(記住這張圖溯饵,后面要考的):
Lifecycle 的設(shè)計(jì)原理
Lifecycle 整體上采用了觀察者模式,主要依賴于三個(gè)類:LifecycleOwner
锨用、LifecycleRegistry
和LifecycleObserver
丰刊。
-
LifecycleOwner: 接口,其實(shí)現(xiàn)類表示具有生命周期增拥,也就是被觀察者啄巧。 Activity 和 Fragment 都實(shí)現(xiàn)了
LifecycleOwner
接口寻歧。
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
public val lifecycle: Lifecycle
}
-
LifecycleRegistry:
Lifecycle
的實(shí)現(xiàn)類,負(fù)責(zé)管理LifecycleOwner
的生命周期狀態(tài)秩仆,并將這些狀態(tài)通知給已注冊的觀察者码泛。每個(gè)LifecycleOwner
都對應(yīng)一個(gè)LifecycleRegistry
。
open class LifecycleRegistry private constructor(
provider: LifecycleOwner,
private val enforceMainThread: Boolean
) : Lifecycle() {
...
private var observerMap = FastSafeIterableMap<LifecycleObserver, ObserverWithState>()
private var state: State = State.INITIALIZED
private val lifecycleOwner: WeakReference<LifecycleOwner>
init {
lifecycleOwner = WeakReference(provider)
}
@MainThread
@Deprecated("Override [currentState].")
open fun markState(state: State) {
enforceMainThreadIfNeeded("markState")
currentState = state
}
...
}
-
LifecycleObserver: 空接口澄耍,表示一個(gè)可以觀察
LifecycleOwner
生命周期狀態(tài)的組件弟晚,也就是觀察者,真正具有使用意義的是它的子接口逾苫。-
LifecycleEventObserver:
LifecycleObserver
的子接口卿城,用于監(jiān)聽Lifecycle
的生命周期變化,可以獲取到生命周期事件發(fā)生的具體變化铅搓。 -
DefaultLifecycleObserver:
LifecycleObserver
的子接口瑟押,用于監(jiān)聽Lifecycle
的生命周期變化,對生命周期的每一種事件都提供了獨(dú)立的方法星掰,適用于只需要知道某些生命周期事件的場景多望。
-
LifecycleEventObserver:
public interface LifecycleObserver
public fun interface LifecycleEventObserver : LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
public fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
}
public interface DefaultLifecycleObserver : LifecycleObserver {
/**
* Notifies that `ON_CREATE` event occurred.
*
*
* This method will be called after the [LifecycleOwner]'s `onCreate`
* method returns.
*
* @param owner the component, whose state was changed
*/
public fun onCreate(owner: LifecycleOwner) {}
/**
* Notifies that `ON_START` event occurred.
*
*
* This method will be called after the [LifecycleOwner]'s `onStart` method returns.
*
* @param owner the component, whose state was changed
*/
public fun onStart(owner: LifecycleOwner) {}
/**
* Notifies that `ON_RESUME` event occurred.
*
*
* This method will be called after the [LifecycleOwner]'s `onResume`
* method returns.
*
* @param owner the component, whose state was changed
*/
public fun onResume(owner: LifecycleOwner) {}
/**
* Notifies that `ON_PAUSE` event occurred.
*
*
* This method will be called before the [LifecycleOwner]'s `onPause` method
* is called.
*
* @param owner the component, whose state was changed
*/
public fun onPause(owner: LifecycleOwner) {}
/**
* Notifies that `ON_STOP` event occurred.
*
*
* This method will be called before the [LifecycleOwner]'s `onStop` method
* is called.
*
* @param owner the component, whose state was changed
*/
public fun onStop(owner: LifecycleOwner) {}
/**
* Notifies that `ON_DESTROY` event occurred.
*
*
* This method will be called before the [LifecycleOwner]'s `onDestroy` method
* is called.
*
* @param owner the component, whose state was changed
*/
public fun onDestroy(owner: LifecycleOwner) {}
}
Lifecycle
整體的設(shè)計(jì)原理如下:
-
LifecycleOwner
在創(chuàng)建時(shí)會創(chuàng)建一個(gè)Lifecycle
實(shí)例。 -
Lifecycle
實(shí)例本質(zhì)就是LifecycleRegistry
氢烘,負(fù)責(zé)管理LifecycleOwner
的生命周期狀態(tài)怀偷,并將這些狀態(tài)通知給已注冊的所有觀察者。 -
LifecycleObserver
在收到狀態(tài)變化通知后播玖,可以根據(jù)狀態(tài)變化執(zhí)行相應(yīng)的操作椎工。
Lifecycle 的使用
Android 預(yù)定義的 LifecycleOwner
有 3 個(gè):Activity
(具體實(shí)現(xiàn)在 androidx.activity.ComponentActivity)、Fragment
和應(yīng)用進(jìn)程級別的 ProcessLifecycleOwner
蜀踏。前兩個(gè)就不多說了维蒙,第3個(gè) ProcessLifecycleOwner
則提供整個(gè)應(yīng)用進(jìn)程級別的生命周期,能夠支持非毫秒級別精度監(jiān)聽?wèi)?yīng)用前后臺切換的場景果覆。
Lifecycle 通過 addObserver(LifecycleObserver)
方法注冊觀察者颅痊,支持通過注解或非注解的方式注冊觀察者,共分為3種方式局待。其中注解方式已被廢棄斑响,在此就不多說了。另外兩種方式分別為注冊一個(gè) LifecycleEventObserver
觀察者和注冊一個(gè) DefaultLifecycleObserver
觀察者钳榨。
/**
* Annotation that can be used to mark methods on {@link LifecycleObserver} implementations that
* should be invoked to handle lifecycle events.
*
* @deprecated This annotation required the usage of code generation or reflection, which should
* be avoided. Use {@link DefaultLifecycleObserver} or
* {@link LifecycleEventObserver} instead.
*/
@SuppressWarnings("unused")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Deprecated
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
注冊一個(gè) LifecycleEventObserver
觀察者舰罚,可以獲取到生命周期事件發(fā)生的具體變化:
lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when (event) {
ON_CREATE -> {}
ON_START -> {}
ON_RESUME -> {}
ON_PAUSE -> {}
ON_STOP -> {}
ON_DESTROY -> {}
ON_ANY -> {}
}
}
})
注冊一個(gè) DefaultLifecycleObserver
觀察者,可以按需重寫生命周期事件監(jiān)聽:
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {}
override fun onStop(owner: LifecycleOwner) {}
override fun onDestroy(owner: LifecycleOwner) {}
})
對于向 ProcessLifecycleOwner
注冊觀察者重绷,需要先通過 ProcessLifecycleOwner.get().lifecycle
的方式獲取 lifecycle:
ProcessLifecycleOwner.get().lifecycle.addObserver(object: LifecycleEventObserver{
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
...
}
})
自定義 LifecycleOwner
Lifecycle 的觀察者必須綁定到 LifecycleOwner 上沸停,一般來說,我們通過對 Android 預(yù)定義的 LifecycleOwner
進(jìn)行 addObserver
即可昭卓,但如果需要自定義 LifecycleOwner愤钾,具體步驟就是實(shí)現(xiàn) LifecycleOwner
并在內(nèi)部將生命周期事件分發(fā)給 Lifecycle 實(shí)現(xiàn)類 LifecycleRegistry
瘟滨。
class MyLifecycleOwner : LifecycleOwner {
private val mLifecycleRegistry = LifecycleRegistry(this)
override fun getLifecycle() = mLifecycleRegistry
fun create() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
fun start() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
fun stop() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
}
...
}
解析 Lifecycle
Lifecycle 注冊觀察者
Lifecycle#addObserver() 最終會分發(fā)到其實(shí)現(xiàn)類 LifecycleRegistry
中,其中會將觀察者和觀察者持有的狀態(tài)包裝為一個(gè)節(jié)點(diǎn)能颁,并且在注冊時(shí)將觀察者狀態(tài)同步推進(jìn)到與宿主 LifecycleOwner 相同的狀態(tài)中杂瘸。
open class LifecycleRegistry private constructor(
provider: LifecycleOwner,
private val enforceMainThread: Boolean
) : Lifecycle() {
...
//生命周期觀察者集合
private var observerMap = FastSafeIterableMap<LifecycleObserver, ObserverWithState>()
//當(dāng)前生命周期狀態(tài),默認(rèn)為初始化狀態(tài)
private var state: State = State.INITIALIZED
//持有生命周期的宿主伙菊,弱引用持有败玉,防止內(nèi)存泄漏
private val lifecycleOwner: WeakReference<LifecycleOwner>
init {
lifecycleOwner = WeakReference(provider)
}
//添加觀察者
override fun addObserver(observer: LifecycleObserver) {
//觀察者的初始狀態(tài):要么是 DESTROYED,要么是 INITIALIZED镜硕,確保觀察者可以接受到完整的事件流
val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
//將觀察者和觀察者持有的狀態(tài)包裝為一個(gè)節(jié)點(diǎn)
val statefulObserver = ObserverWithState(observer, initialState)
//加入到觀察者集合中
val previous = observerMap.putIfAbsent(observer, statefulObserver)
//如果上一步添加成功了运翼,putIfAbsent會返回null
if (previous != null) {
return
}
//生命周期宿主已被回收,直接return
val lifecycleOwner = lifecycleOwner.get()
?: // it is null we should be destroyed. Fallback quickly
return
//當(dāng)前在添加的觀察者數(shù)量!=0||正在處理事件
val isReentrance = addingObserverCounter != 0 || handlingEvent
//將觀察者推進(jìn)到宿主最新的狀態(tài)兴枯,先獲取到最新狀態(tài)
var targetState = calculateTargetState(observer)
addingObserverCounter++
//如果當(dāng)前觀察者狀態(tài)小于當(dāng)前生命周期所在狀態(tài)&&這個(gè)觀察者已經(jīng)被存到了觀察者列表中
//while一直循環(huán)血淌,直到觀察者狀態(tài)同步到當(dāng)前生命周期所在狀態(tài)
while (statefulObserver.state < targetState && observerMap.contains(observer)
) {
//保存當(dāng)前的生命周期狀態(tài)
pushParentState(statefulObserver.state)
//返回當(dāng)前生命周期狀態(tài)對應(yīng)的接下來的事件序列
val event = Event.upFrom(statefulObserver.state)
?: throw IllegalStateException("no event up from ${statefulObserver.state}")
//分發(fā)事件
statefulObserver.dispatchEvent(lifecycleOwner, event)
//移除當(dāng)前的生命周期狀態(tài)
popParentState()
//再次獲得當(dāng)前的最新狀態(tài)
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer)
}
//處理一遍事件,保證事件同步
if (!isReentrance) {
// we do sync only on the top level.
sync()
}
addingObserverCounter--
}
//移除觀察者
override fun removeObserver(observer: LifecycleObserver) {
observerMap.remove(observer)
}
//觀察者及其觀察狀態(tài)
internal class ObserverWithState(observer: LifecycleObserver?, initialState: State) {
var state: State
var lifecycleObserver: LifecycleEventObserver
init {
//用適配器包裝觀察者财剖,實(shí)現(xiàn)對不同類型觀察者的統(tǒng)一分發(fā)
lifecycleObserver = Lifecycling.lifecycleEventObserver(observer!!)
state = initialState
}
fun dispatchEvent(owner: LifecycleOwner?, event: Event) {
val newState = event.targetState
state = min(state, newState)
//通知觀察者
lifecycleObserver.onStateChanged(owner!!, event)
state = newState
}
}
...
}
Lifecycle
注冊觀察者的邏輯就是上面這些了悠夯,主要步驟如下:
- 初始化觀察者的狀態(tài)。
- 將觀察者和觀察者持有的狀態(tài)包裝為一個(gè)節(jié)點(diǎn)躺坟。
- 將觀察者和其狀態(tài)加入到 map 集合中沦补。
- 獲取當(dāng)前 LifecycleOwner 生命周期狀態(tài)。
- while 循環(huán)咪橙,將觀察者狀態(tài)同步推進(jìn)到與宿主 LifecycleOwner 相同的狀態(tài)夕膀。
Lifecycle 適配不同類型的觀察者
上面說到了注冊觀察者的時(shí)候會將觀察者和觀察者持有的狀態(tài)包裝為一個(gè)節(jié)點(diǎn) ObserverWithState
,而在 ObserverWithState
中會將外部傳入的所有 LifecycleObserver
通過 Lifecycling
包裝成 LifecycleEventObserver
對象匣摘。之所以要這么做就是為了適配不同類型的觀察者店诗,Lifecycling 就是適配層。
-
LifecycleObserver
本身是個(gè)空接口音榜,實(shí)際使用的是它兩個(gè)子接口LifecycleEventObserver
和DefaultLifecycleObserver
,開發(fā)者自己實(shí)現(xiàn)的自定義 Observer 可能同時(shí)實(shí)現(xiàn)了這兩個(gè)接口或者實(shí)現(xiàn)了任一接口捧弃,LifecycleRegistry
必須在有事件觸發(fā)的時(shí)候通知觀察者存在的所有接口方法赠叼。 - 上面講到注冊觀察者的方式還有注解的方式(雖然現(xiàn)已被廢棄),但是這種方式下就需要通過反射來實(shí)現(xiàn)事件通知了违霞。
Lifecycling 作為適配層嘴办,其作用就是對外部傳入的 Observer 進(jìn)行類型判斷、接口回調(diào)买鸽、反射調(diào)用等一系列操作涧郊,將這一系列的邏輯給封裝起來,對傳入的 Observer 統(tǒng)一包裝成 LifecycleEventObserver
對象眼五,僅僅開放一個(gè) onStateChanged
方法即可讓 LifecycleRegistry
完成整個(gè)事件分發(fā)妆艘,從而使得整個(gè)流程會更加清晰明了且職責(zé)分明彤灶。
public object Lifecycling {
@JvmStatic
@Suppress("DEPRECATION")
public fun lifecycleEventObserver(`object`: Any): LifecycleEventObserver {
val isLifecycleEventObserver = `object` is LifecycleEventObserver
val isDefaultLifecycleObserver = `object` is DefaultLifecycleObserver
// 1. 觀察者同時(shí)實(shí)現(xiàn) LifecycleEventObserver 和 DefaultLifecycleObserver
if (isLifecycleEventObserver && isDefaultLifecycleObserver) {
return DefaultLifecycleObserverAdapter(
`object` as DefaultLifecycleObserver,
`object` as LifecycleEventObserver
)
}
// 2. 觀察者只實(shí)現(xiàn) DefaultLifecycleObserver
if (isDefaultLifecycleObserver) {
return DefaultLifecycleObserverAdapter(`object` as DefaultLifecycleObserver, null)
}
// 3. 觀察者只實(shí)現(xiàn) LifecycleEventObserver
if (isLifecycleEventObserver) {
return `object` as LifecycleEventObserver
}
// 4. 觀察者使用注解方式
val klass: Class<*> = `object`.javaClass
val type = getObserverConstructorType(klass)
if (type == GENERATED_CALLBACK) {
val constructors = classToAdapters[klass]!!
if (constructors.size == 1) {
val generatedAdapter = createGeneratedAdapter(
constructors[0], `object`
)
return SingleGeneratedAdapterObserver(generatedAdapter)
}
val adapters: Array<GeneratedAdapter> = Array(constructors.size) { i ->
createGeneratedAdapter(constructors[i], `object`)
}
return CompositeGeneratedAdaptersObserver(adapters)
}
// 反射調(diào)用
return ReflectiveGenericLifecycleObserver(`object`)
}
}
DefaultLifecycleObserverAdapter
實(shí)現(xiàn)了 LifecycleEventObserver
接口,用于在收到 Lifecycle
生命周期事件狀態(tài)變化時(shí)批旺,對兩個(gè)構(gòu)造參數(shù) DefaultLifecycleObserver
幌陕、LifecycleEventObserver
進(jìn)行事件轉(zhuǎn)發(fā)。
internal class DefaultLifecycleObserverAdapter(
private val defaultLifecycleObserver: DefaultLifecycleObserver,
private val lifecycleEventObserver: LifecycleEventObserver?
) : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when (event) {
Lifecycle.Event.ON_CREATE -> defaultLifecycleObserver.onCreate(source)
Lifecycle.Event.ON_START -> defaultLifecycleObserver.onStart(source)
Lifecycle.Event.ON_RESUME -> defaultLifecycleObserver.onResume(source)
Lifecycle.Event.ON_PAUSE -> defaultLifecycleObserver.onPause(source)
Lifecycle.Event.ON_STOP -> defaultLifecycleObserver.onStop(source)
Lifecycle.Event.ON_DESTROY -> defaultLifecycleObserver.onDestroy(source)
Lifecycle.Event.ON_ANY ->
throw IllegalArgumentException("ON_ANY must not been send by anybody")
}
lifecycleEventObserver?.onStateChanged(source, event)
}
}
Lifecycle 分發(fā)生命周期事件
在注冊觀察者的時(shí)候汽煮,將觀察者狀態(tài)同步推進(jìn)到與宿主 LifecycleOwner 相同的狀態(tài)搏熄,用的是 while 循環(huán),每一次獲取當(dāng)前狀態(tài)接下來的事件并進(jìn)行事件分發(fā)暇赤,一次一步心例,直到狀態(tài)同步。
public enum class Event {
public companion object {
/**
* Returns the [Lifecycle.Event] that will be reported by a [Lifecycle]
* leaving the specified [Lifecycle.State] to a higher state, or `null`
* if there is no valid event that can move up from the given state.
*
* @param state the lower state that the returned event will transition up from
* @return the event moving up the lifecycle phases from state
*/
@JvmStatic
public fun upFrom(state: State): Event? {
return when (state) {
State.INITIALIZED -> ON_CREATE
State.CREATED -> ON_START
State.STARTED -> ON_RESUME
else -> null
}
}
}
}
結(jié)合 Lifecycle 分發(fā)生命周期狀態(tài)的流程圖:
如果在 Activity onResume 之后向其添加了一個(gè) LifecycleEventObserver鞋囊,此時(shí)觀察者初始狀態(tài)是 INITIALIZED止后,需要同步到與宿主 LifecycleOwner 相同的狀態(tài),也就是RESUMED失暴,觀察者會依次收到 ON_CREATE坯门、ON_START、ON_RESUME 三個(gè)Event事件逗扒。
當(dāng)宿主 LifecycleOwner 生命周期發(fā)生變化時(shí)古戴,會將生命周期事件分發(fā)到 LifecycleRegistry#handleLifecycleEvent(Lifecycle.Event)
,將觀察者的狀態(tài)回調(diào)到最新的狀態(tài)上矩肩。
//分發(fā)生命周期事件
open fun handleLifecycleEvent(event: Event) {
moveToState(event.targetState)
}
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
//狀態(tài)同步
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) {
//狀態(tài)回退
backwardPass(lifecycleOwner)
}
val newest = observerMap.newest()
if (!newEventOccurred && newest != null && state > newest.value.state) {
//狀態(tài)前進(jìn)
forwardPass(lifecycleOwner)
}
}
newEventOccurred = false
}
private fun forwardPass(lifecycleOwner: LifecycleOwner) {
@Suppress()
val ascendingIterator: Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> =
observerMap.iteratorWithAdditions()
while (ascendingIterator.hasNext() && !newEventOccurred) {
val (key, observer) = ascendingIterator.next()
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()
}
}
}
首先更新狀態(tài) state
现恼,然后通過 sync()
方法將狀態(tài)同步到所有觀察者,sync() 方法在添加觀察者時(shí)也被調(diào)用過黍檩。在 sync() 方法中叉袍,狀態(tài)需要回退則調(diào)用 backwardPass
方法,狀態(tài)需要前進(jìn)則調(diào)用 forwardPass
方法刽酱。兩個(gè)方法邏輯相似喳逛,這邊就只貼出了 forwardPass
方法,來看一下如何處理狀態(tài)前進(jìn)的棵里∪笪模可以發(fā)現(xiàn)里面使用了兩層 while 循環(huán),外層 while 循環(huán)遍歷所有觀察者殿怜,內(nèi)層 while 循環(huán)與注冊觀察者時(shí)狀態(tài)同步的 while 循環(huán)內(nèi)容一致典蝌,每一次獲取當(dāng)前狀態(tài)接下來的事件并進(jìn)行事件分發(fā),一次一步头谜,直到狀態(tài)同步骏掀。
最終 observer.dispatchEvent
是通過 ObserverWithState#dispatchEvent()
分發(fā)事件,我們已經(jīng)知道 ObserverWithState 里使用了適配器模式對 Observer 統(tǒng)一包裝成 LifecycleEventObserver
對象,僅僅開放一個(gè) onStateChanged
方法截驮,ObserverWithState#dispatchEvent()
里就是通過 lifecycleObserver.onStateChanged
通知到觀察者笑陈,后續(xù)就是上一點(diǎn)提到的 Lifecycling
適配層的邏輯了。
Lifecycle 感知 Activity 生命周期
知道了怎么注冊的觀察者以及如何將生命周期事件分發(fā)到觀察者侧纯,最后來看一下 Lifecycle 是如何感知到宿主 LifecycleOwner 的生命周期進(jìn)而繼續(xù)后續(xù)的操作的新锈。
上面講到當(dāng)宿主 LifecycleOwner 生命周期發(fā)生變化時(shí),會將生命周期事件分發(fā)到 LifecycleRegistry#handleLifecycleEvent(Lifecycle.Event)
眶熬,這不就簡單了妹笆,在宿主 LifecycleOwner 生命周期的相關(guān)方法直接調(diào)用不就好了。
通過查看 LifecycleRegistry#handleLifecycleEvent
的調(diào)用娜氏,可以看到在 Dialog
拳缠、Fragment
、FragmenActivity
里就是通過在生命周期的相關(guān)方法里直接調(diào)用 LifecycleRegistry#handleLifecycleEvent(Lifecycle.Event)
將生命周期事件分發(fā)的贸弥,但是并沒有出現(xiàn)我們常用的 ComponentActivity
窟坐,這是因?yàn)樯鲜鲞@種方法會造成對基類的入侵,使得基類越發(fā)膨脹绵疲,所以在 ComponentActivity
中使用了 ReportFragment
承載 Lifecycle 在 activity 的具體邏輯哲鸳。
感知宿主生命周期使用 ReportFragment
,管理生命周期狀態(tài)并將狀態(tài)通知觀察者使用 LifecycleRegistry
盔憨,適配觀察者使用 Lifecycling
徙菠,這一整套流程行云流水清晰明了且職責(zé)分明。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner ...{
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
...
}
}
通過 ReportFragment#injectIfNeededIn(Activity)
接收 Activity郁岩。
open class ReportFragment() : android.app.Fragment() {
companion object {
@JvmStatic
fun 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
val manager = activity.fragmentManager
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(ReportFragment(), REPORT_FRAGMENT_TAG).commit()
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions()
}
}
}
}
- 第一種情況:在sdk29以下婿奔,通過向 Activity 添加一個(gè)空白界面的 Fragment,間接獲得 Activity 的各個(gè)生命周期事件的回調(diào)通知问慎。
- 第二種情況:在sdk29及以上萍摊,通過向 Activity 注冊生命周期回調(diào)的方式來監(jiān)聽。這里應(yīng)該還牽扯到對舊版本 ProcessLifecycleOwner 和 support 庫的兼容如叼,所以此時(shí)也會同時(shí)執(zhí)行第一種情況的操作冰木。
之所以這么區(qū)分是因?yàn)?registerActivityLifecycleCallbacks
中的 onActivityPostXXX
和 onActivityPreXXX
等方法是sdk29時(shí)新添加的方法。
@RequiresApi(29)
internal class LifecycleCallbacks : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(
activity: Activity,
bundle: Bundle?
) {}
override fun onActivityPostCreated(
activity: Activity,
savedInstanceState: Bundle?
) {
dispatch(activity, Lifecycle.Event.ON_CREATE)
}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityPostStarted(activity: Activity) {
dispatch(activity, Lifecycle.Event.ON_START)
}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPostResumed(activity: Activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME)
}
override fun onActivityPrePaused(activity: Activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE)
}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityPreStopped(activity: Activity) {
dispatch(activity, Lifecycle.Event.ON_STOP)
}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(
activity: Activity,
bundle: Bundle
) {}
override fun onActivityPreDestroyed(activity: Activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY)
}
override fun onActivityDestroyed(activity: Activity) {}
companion object {
@JvmStatic
fun registerIn(activity: Activity) {
activity.registerActivityLifecycleCallbacks(LifecycleCallbacks())
}
}
}
一些小細(xì)節(jié)笼恰,在sdk29及以上片酝,通過向 Activity 注冊生命周期回調(diào)的方式來監(jiān)聽時(shí),會在 Activity 的 onCreate挖腰、onStart、onResume
等方法被調(diào)用后發(fā)送相應(yīng)的 Event 事件练湿,并在 onPause猴仑、onStop、onDestroy
等方法被調(diào)用前發(fā)送相應(yīng)的 Event 事件。
Lifecycle 的運(yùn)用實(shí)踐案例
Lifecycle
作為 JetPack
的基石辽俗,在 JetPack
里已有了許多的運(yùn)用實(shí)踐:
- LifecycleOwner.lifecycleScope疾渣,具有生命周期感知的協(xié)程作用域,當(dāng)宿主 destroy 時(shí)崖飘,會自動取消協(xié)程榴捡。
- LiveData,具有生命周期感知能力朱浴,當(dāng)宿主狀態(tài)活躍時(shí)(狀態(tài)至少為 STARTED)吊圾,才會發(fā)送數(shù)據(jù),同時(shí)當(dāng)宿主 destroy 時(shí)翰蠢,會自動移除觀察者项乒。
- Flow#flowWithLifecycle(),當(dāng)宿主狀態(tài)活躍時(shí)(默認(rèn)狀態(tài)至少為 STARTED)梁沧,啟動一個(gè)新協(xié)程用于接收 flow 數(shù)據(jù)檀何,當(dāng)宿主狀態(tài)不活躍時(shí),取消該協(xié)程廷支。