Lifecycle源码解析
源码版本:
- Lifecycle:2.8.7
- androidx.activity:activity:1.10.1
- androidx.fragment:fragment:1.8.6
- 更新时间:2025-3月
导航:
使用
声明LifecycleObserver
1. DefaultLifecycleObserver
生命周期状态改变时,会调用对应的方法。可根据需要,重写某个方法。
val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
}
}
2. LifecycleEventObserver
生命周期状态改变时,会调用onStateChanged
方法。
val lifecycleObserver = object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
}
}
3. OnLifecycleEvent(已弃用)
生命周期状态改变时,会调用LifecycleObserver
子类被对应event标注的方法。使用OnLifecycleEvent
注解标注方法上,方法要求:方法名称任意,方法参数可无、可1个(必须是LifecycleOwner
)、可2个(必须先后是LifecycleOwner
、Lifecycle.Event
、且event
必须是Lifecycle.Event.ON_ANY
)。
val lifecycleObserver = object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(owner: LifecycleOwner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny(owner: LifecycleOwner, event: Lifecycle.Event) {
}
}
添加Observer
lifecycle.addObserver(lifecycleObserver)
移除Observer
lifecycle.removeObserver(lifecycleObserver)
获取当前State
val currentState = lifecycle.currentState
val currentStateFlow = lifecycle.currentStateFlow
获取当前Event
val eventFlow = lifecycle.eventFlow
源码
声明LifecycleObserver
1. DefaultLifecycleObserver
DefaultLifecycleObserver接口
public interface DefaultLifecycleObserver : LifecycleObserver {
public fun onCreate(owner: LifecycleOwner) {}
public fun onStart(owner: LifecycleOwner) {}
public fun onResume(owner: LifecycleOwner) {}
public fun onPause(owner: LifecycleOwner) {}
public fun onStop(owner: LifecycleOwner) {}
public fun onDestroy(owner: LifecycleOwner) {}
}
DefaultLifecycleObserver
接口,继承LifecycleObserver
接口,并进行了生命周期方法默认空实现,所以可以按需实现某个方法。
LifecycleObserver接口
public interface LifecycleObserver
LifecycleObserver
是一个空接口,用于标记可以被Lifecycle
添加、删除。可以使用它的子接口DefaultLifecycleObserver
、LifecycleEventObserver
或被OnLifecycleEvent(已弃用)
标注方法的子类,来通知生命周期事件,详细见后面-ObserverWithState
。
2. LifecycleEventObserver
LifecycleEventObserver接口
public fun interface LifecycleEventObserver : LifecycleObserver {
public fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
}
LifecycleEventObserver
接口,为生命周期状态改变时,会调用onStateChanged
方法(详细见后面-ObserverWithState
)。参数event
为当前的事件(ON_CREATE
、ON_START
、ON_RESUME
、ON_PAUSE
、ON_STOP
、ON_DESTROY
)。
3. OnLifecycleEvent(已弃用)
OnLifecycleEvent注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Deprecated
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
OnLifecycleEvent
注解,当生命周期状态改变时,会调用LifecycleObserver
子类被对应event标注的方法(详细见后面-ObserverWithState
)。OnLifecycleEvent
已被@Deprecated
标注,已经被弃用,后面会减少对此的讲解。
接下来,我们来看一下是如果把上面3种情况的LifecycleObserver
统一的(好方便统一分发事件),以及是如何分发事件的。
统一LifecycleObserver
ObserverWithState类
internal class ObserverWithState(observer: LifecycleObserver?, initialState: State) {
var state: State
var lifecycleObserver: LifecycleEventObserver
init {
// 把上面全部3种情况的LifecycleObserver统一转换成LifecycleEventObserver。
lifecycleObserver = Lifecycling.lifecycleEventObserver(observer!!)
state = initialState
}
fun dispatchEvent(owner: LifecycleOwner?, event: Event) {
val newState = event.targetState
state = min(state, newState)
// 用转换后的LifecycleEventObserver通知原始observer状态改变。
lifecycleObserver.onStateChanged(owner!!, event)
state = newState
}
}
ObserverWithState
为带状态的观察者,它统一了全部3种情况的LifecycleObserver
为LifecycleEventObserver
;以及dispatchEvent()
方法,用转换后的LifecycleEventObserver
通知原始observer
状态改变。我们再来看一下Lifecycling
它是如何统一的。
Lifecycling --> lifecycleEventObserver方法
public actual fun lifecycleEventObserver(`object`: Any): LifecycleEventObserver {
// 是否是LifecycleEventObserver子类
val isLifecycleEventObserver = `object` is LifecycleEventObserver
// 是否是DefaultLifecycleObserver子类
val isDefaultLifecycleObserver = `object` is DefaultLifecycleObserver
if (isLifecycleEventObserver && isDefaultLifecycleObserver) {
// 两者都是,需要适配,两个样式回调都通知。
return DefaultLifecycleObserverAdapter(
`object` as DefaultLifecycleObserver,
`object` as LifecycleEventObserver
)
}
if (isDefaultLifecycleObserver) {
// 只是DefaultLifecycleObserver,需要适配,只回调一个。
return DefaultLifecycleObserverAdapter(`object` as DefaultLifecycleObserver, null)
}
if (isLifecycleEventObserver) {
// 只是LifecycleEventObserver,即为结果,不用适配,直接返回即可。
return `object` as LifecycleEventObserver
}
// 使用OnLifecycleEvent注解的处理
val klass: Class<*> = `object`.javaClass
val type = getObserverConstructorType(klass)
if (type == GENERATED_CALLBACK) {
// 使用OnLifecycleEvent注解,并且依赖了androidx.lifecycle:lifecycle-compiler注解处理器,使用注解处理器优化反射带来的性能问题。
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)
}
// 使用OnLifecycleEvent注解,并且未依赖注解处理器,使用反射处理。
return ReflectiveGenericLifecycleObserver(`object`)
}
lifecycleEventObserver()
方法,将参数LifecycleObserver
转为统一的LifecycleEventObserver
。
说明:
上面3种
LifecycleObserver
情况适配:
- 只是
LifecycleEventObserver
:即为结果,不用适配。- 只是
DefaultLifecycleObserver
、两者都是:使用DefaultLifecycleObserverAdapter
适配。OnLifecycleEvent
注解:使用SingleGeneratedAdapterObserver
或CompositeGeneratedAdaptersObserver
或ReflectiveGenericLifecycleObserver
适配。
由于只是LifecycleEventObserver
,不需要适配,所以我们接下来看下DefaultLifecycleObserverAdapter
的适配。
DefaultLifecycleObserverAdapter
DefaultLifecycleObserverAdapter类
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)
}
}
DefaultLifecycleObserverAdapter
类,为DefaultLifecycleObserver
情况做适配,但是为了兼容性,支持一个类同时实现DefaultLifecycleObserver
、LifecycleEventObserver
的情况。
和OnLifecycleEvent
注解相关的适配器有3个,由于OnLifecycleEvent
已经弃用,所以我们只讲1个反射的,我们接下来看下ReflectiveGenericLifecycleObserver
的适配。
ReflectiveGenericLifecycleObserver
ReflectiveGenericLifecycleObserver类
@Deprecated
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final androidx.lifecycle.ClassesInfoCache.CallbackInfo mInfo;
@SuppressWarnings("deprecation")
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
// 获取观察者类的信息,内部会解析判断被OnLifecycleEvent注解的方法声明是否正确。
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
// 调用被OnLifecycleEvent标注的对应的方法,通知回调。
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
ReflectiveGenericLifecycleObserver
类,为使用OnLifecycleEvent
注解并且无使用androidx.lifecycle:lifecycle-compiler
注解处理器情况做适配。
ClassesInfoCache --> getInfo方法
CallbackInfo getInfo(Class<?> klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
ClassesInfoCache
类的getInfo
方法,一开始缓存里面是没有的,然后会调用createInfo()
方法进行创建并存储到缓存并返回其结果。
ClassesInfoCache --> createInfo方法
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
...
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
// 第1个参数必须是LifecycleOwner,否则抛异常。
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
// 第2个参数必须是Lifecycle.Event,否则抛异常。
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
// 并且OnLifecycleEvent注解的值必须是Lifecycle.Event.ON_ANY,否则抛异常。
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
// 超过2个参数,报错。
throw new IllegalArgumentException("cannot have more than 2 params");
}
...
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
// 存储到缓存
mCallbackMap.put(klass, info);
...
return info;
}
说明:
- 使用
OnLifecycleEvent
注解标注方法上,方法要求:方法名称任意,方法参数可无、可1个(必须是LifecycleOwner
)、可2个(必须先后是LifecycleOwner
、Lifecycle.Event
、且event
必须是Lifecycle.Event.ON_ANY
)。
小结
说明:
ObserverWithState
为带状态的观察者,它统一了全部3种情况的LifecycleObserver
为LifecycleEventObserver
;以及dispatchEvent()
方法,用转换后的LifecycleEventObserver
通知原始observer
状态改变。
上面使用的添加、删除、获取当前状态等,都是要先获取到当前的Lifecycle
的,我们先来看一下Lifecycle
类的定义,再看一下Activity
、Fragment
是如何获取Lifecycle
的。
获取Lifecycle
Lifecycle类
public abstract class Lifecycle {
// 协程相关,存放coroutineScope的。
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@set:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public var internalScopeRef: AtomicReference<Any?> = AtomicReference(null)
// 添加观察者
@MainThread
public abstract fun addObserver(observer: LifecycleObserver)
// 移除观察者
@MainThread
public abstract fun removeObserver(observer: LifecycleObserver)
// 获取当前的状态
@get:MainThread
public abstract val currentState: State
// 获取当前的状态-Flow
public open val currentStateFlow: StateFlow<Lifecycle.State>
get() {
val mutableStateFlow = MutableStateFlow(currentState)
LifecycleEventObserver { _, event ->
mutableStateFlow.value = event.targetState
}.also { addObserver(it) } // 通过addObserver()来观察,获取当前Event的State。
return mutableStateFlow.asStateFlow()
}
// 事件类
public enum class Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY; // 任何事件都会触发
// 返回此Event的对应的State。
// 如果ON_ANY被调用,抛出IllegalArgumentException,因为它是OnLifecycleEvent使用的特殊值,而不是一个真正的生命周期Event。
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")
}
public companion object {
// 以下为State转Event相关
@JvmStatic
public fun downFrom(state: State): Event? {
return when (state) {
State.CREATED -> ON_DESTROY
State.STARTED -> ON_STOP
State.RESUMED -> ON_PAUSE
else -> null
}
}
@JvmStatic
public fun downTo(state: State): Event? {
return when (state) {
State.DESTROYED -> ON_DESTROY
State.CREATED -> ON_STOP
State.STARTED -> ON_PAUSE
else -> null
}
}
@JvmStatic
public fun upFrom(state: State): Event? {
return when (state) {
State.INITIALIZED -> ON_CREATE
State.CREATED -> ON_START
State.STARTED -> ON_RESUME
else -> null
}
}
@JvmStatic
public fun upTo(state: State): Event? {
return when (state) {
State.CREATED -> ON_CREATE
State.STARTED -> ON_START
State.RESUMED -> ON_RESUME
else -> null
}
}
}
}
// 状态类
public enum class State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
// 比较这个状态是否大于等于给定的状态,RESUMED > STARTED > CREATED > INITIALIZED > DESTROYED。
public fun isAtLeast(state: State): Boolean {
return compareTo(state) >= 0
}
}
}
State
和Event
的关系图
我们再来看一下,从Actvity
、Fragment
中是如何获取到Lifecycle
的,因为androidx.activity.ComponentActivity
和androidx.fragment.app.Fragment
都实现了LifecycleOwner
接口,表明可以提供Lifecycle
实例,相关的源码如下:
LifecycleOwner接口
public interface LifecycleOwner {
public val lifecycle: Lifecycle
}
我们先来看下Activity
的LifecycleOwner
接口的实现
Activity
androidx.activity.ComponentActivity --> lifecycle
open class ComponentActivity() :
androidx.core.app.ComponentActivity(),
ContextAware,
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner,
ActivityResultRegistryOwner,
ActivityResultCaller,
OnConfigurationChangedProvider,
OnTrimMemoryProvider,
OnNewIntentProvider,
OnMultiWindowModeChangedProvider,
OnPictureInPictureModeChangedProvider,
OnUserLeaveHintProvider,
MenuHost,
FullyDrawnReporterOwner {
override val lifecycle: Lifecycle
get() = super.lifecycle
}
androidx.activity.ComponentActivity
的lifecycle
,调用了父类的,我们再来父类的。
androidx.core.app.ComponentActivity --> getLifecycle方法
public open class ComponentActivity : Activity(), LifecycleOwner, KeyEventDispatcher.Component {
@Suppress("LeakingThis") private val lifecycleRegistry = LifecycleRegistry(this)
override val lifecycle: Lifecycle
get() = lifecycleRegistry
}
androidx.core.app.ComponentActivity
的lifecycle
,获取了LifecycleRegistry
实例,我们先来看Fragment
的实现,然后再看LifecycleRegistry
源码。
说明:
MyActivity
继承关系:MyActivity
->AppCompatActivity
->FragmentActivity
->androidx.activity.ComponentActivity
->androidx.core.app.ComponentActivity
我们接下来看下Fragment
的LifecycleOwner
接口的实现
Fragment
androidx.fragment.app.Fragment --> getLifecycle方法
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner,
ActivityResultCaller {
LifecycleRegistry mLifecycleRegistry;
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
}
}
androidx
的Activity
、Fragment
都实现了LifecycleOwner
接口,并返回的都是LifecycleRegistry
实例(拿到lifecycle
后的所有操作都是操作的此类),我们接下来看一下LifecycleRegistry
类的构造方法。
LifecycleRegistry --> 构造方法
public actual open class LifecycleRegistry private constructor(
provider: LifecycleOwner,
// 是否强制在主线程执行
private val enforceMainThread: Boolean
) : Lifecycle() {
public actual constructor(provider: LifecycleOwner) : this(provider, true) // 默认,强制在主线程执行。
}
LifecycleRegistry
类,继承Lifecycle
类,androidx
的Activity
、Fragment
都使用了LifecycleRegistry(this)
,所以他们都是强制在主线程执行。
小结
说明:
androidx
的Activity
、Fragment
获取Lifecycle
,获取的都是Lifecycle
的实现类LifecycleRegistry
,后续的操作都是操作的此,并且有些操作要求只能在主线程执行。
添加Observer
LifecycleRegistry --> addObserver()方法
override fun addObserver(observer: LifecycleObserver) {
// 当enforceMainThread为true时,必须是在主线程调用,否则抛出异常
enforceMainThreadIfNeeded("addObserver")
// 观察者的初始化状态
val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
// 生成ObserverWithState,它包含状态和观察者,它会把上面全部3种情况的LifecycleObserver统一转换成LifecycleEventObserver。
val statefulObserver = ObserverWithState(observer, initialState)
// 将观察者添加到map,如果已经添加,则直接返回。
// putIfAbsent,如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,并返回null。
val previous = observerMap.putIfAbsent(observer, statefulObserver)
if (previous != null) {
// 之前有此观察者,则直接返回。
return
}
// 获取LifecycleOwner实例,一般来说是Activity或者Fragment实例。
val lifecycleOwner = lifecycleOwner.get()
?: // 对象为空,说明已经被销毁,直接返回。
return
// isReentrance:是否是再次进入
// 1.addingObserverCounter:添加中的观察者数量。在执行前加1,在执行后减1,又因为addObserver方法强制在主线程执行(没有并发),所以它一般都为0。之所以不为0,是因为它在添加的observer的生命周期回调的方法内,又调用addObserver方法增加了一个新的LifecycleObserver。
// 2.handlingEvent:是否正在处理事件中。
val isReentrance = addingObserverCounter != 0 || handlingEvent
// 计算目标状态
var targetState = calculateTargetState(observer)
// 增加中的观察者数量加1
addingObserverCounter++
// statefulObserver.state < targetState:说明观察者ObserverWithState的状态未到达目标状态。
// observerMap.contains(observer):上面已observerMap.putIfAbsent()判断,这边再判断是否包含,是因为它在添加的observer的生命周期回调的方法内,可能调用了removeObserver。
// 使用while,保证依次分发所有的事件。
while (statefulObserver.state < targetState && observerMap.contains(observer)) {
// 父状态添加一个
pushParentState(statefulObserver.state)
// 获取观察者状态的下一个事件
val event = Event.upFrom(statefulObserver.state)
?: throw IllegalStateException("no event up from ${statefulObserver.state}")
// 观察者ObserverWithState分发事件,通知被Lifecycle添加的LifecycleObserver状态改变。
statefulObserver.dispatchEvent(lifecycleOwner, event)
// 父状态移除一个
popParentState()
// 目标状态可能被更改,重新计算
targetState = calculateTargetState(observer)
}
if (!isReentrance) {
// 不是再次进入,同步。
sync()
}
// 增加中的观察者数量减1
addingObserverCounter--
}
addObserver(observer)
方法,将此observer
包装为带有状态的ObserverWithState
,如果此包装者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。
说明:
addObserver(observer)
,只能在主线程执行。targetState
一般为state
(当前状态),观察者ObserverWithState
初始化状态一般为INITIALIZED
,如果此包装者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。例如:如果在Activity
的onResume
后addObserver
,则当前状态为RESUMED
,观察者的状态为INITIALIZED
到RESUMED
,所以此观察者会依次接收到ON_CREATE
、ON_START
、ON_RESUME
事件的回调。
小结
代码流程:
LifecycleRegistry
类addObserver()
方法,会把观察者和状态的包装为ObserverWithState
,并添加到observerMap
集合以记录所有观察者,并且添加时会通知此观察者分发事件,所以此自带粘性效果。- 如果观察者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止,所以添加时会依次收到多个事件。
移除Observer
LifecycleRegistry --> removeObserver方法
override fun removeObserver(observer: LifecycleObserver) {
// 当enforceMainThread为true时,必须是在主线程调用,否则抛出异常
enforceMainThreadIfNeeded("removeObserver")
// 从map中移除
observerMap.remove(observer)
}
removeObserver()
方法,从observerMap
中移除。
获取当前State
currentState
LifecycleRegistry --> currentState
actual override var currentState: State
get() = state
set(state) {
// 当enforceMainThread为true时,必须是在主线程调用,否则抛出异常
enforceMainThreadIfNeeded("setCurrentState")}
// 将生命周期移动到给定state并将必要的事件发送给观察者。
moveToState(state)
}
getCurrentState()
方法,为获取到当前的状态。setCurrentState()
方法,为设置当前的状态(将状态移动到给定值)。
currentStateFlow
LifecycleRegistry --> currentStateFlow
private val _currentStateFlow: MutableStateFlow<State> = MutableStateFlow(State.INITIALIZED)
override val currentStateFlow: StateFlow<State>
get() = _currentStateFlow.asStateFlow()
getCurrentStateFlow()
方法,为获取到当前状态的Flow
,_currentStateFlow
会在sync()
方法时记录当前状态。
获取当前Event
public val Lifecycle.eventFlow: Flow<Lifecycle.Event>
get() = callbackFlow {
val observer = LifecycleEventObserver { _, event ->
trySend(event)
}.also { addObserver(it) } // 通过addObserver()来观察,获取当前Event。
awaitClose { removeObserver(observer) }
}.flowOn(Dispatchers.Main.immediate)
getEventFlow()
方法,为获取到当前事件的Flow
,内部使用addObserver()
来观察获取当前Event
。
此状态是如何被通知的,它又是如何感知生命周期的,我们一起看生命周期感知。
生命周期感知
Lifecycle
是一个生命周期感知的框架,那么它是如何感知Activity
或Fragment
的生命周期的呢?
Activity
说明:
MyActivity
继承关系:MyActivity
->AppCompatActivity
->FragmentActivity
->androidx.activity.ComponentActivity
->androidx.core.app.ComponentActivity
androidx.activity.ComponentActivity--> onCreate方法
override fun onCreate(savedInstanceState: Bundle?) {
...
super.onCreate(savedInstanceState)
// 使用ReportFragment分发事件
ReportFragment.injectIfNeededIn(this)
if (contentLayoutId != 0) {
setContentView(contentLayoutId)
}
}
androidx.core.app.ComponentActivity--> onCreate方法
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 使用ReportFragment分发事件
ReportFragment.injectIfNeededIn(this)
}
androidx.activity.ComponentActivity
、它的父类androidx.core.app.ComponentActivity
都调用了ReportFragment.injectIfNeededIn(this)
,让其处理当前Activity
的事件分发。
问题:
- 为什么在
androidx.activity.ComponentActivity
内调用了,还要在其父类androidx.core.app.ComponentActivity
内调用?
- 因为
MyActivity
可能直接继承的是父类androidx.core.app.ComponentActivity
。- 上面问题,会导致同一个
Activity
调用了多次,那addObserver
增加的观察者会不会同一个状态被通知多次?
- 不会,因为在
LifecycleRegistry
分发的时候,判断了,如果要分发的状态和当前的状态相同,则不操作直接返回,所以不会被被通知多次。- 为什么要用
Fragment
来实现Activity
的事件分发?
- 因为
Fragment
能感知生命周期变化,并且Fragment
好在Activity
中进行增删,例如MyActivity
直接继承Activity
,想要此功能,直接在onCreate
方法内调用ReportFragment.injectIfNeededIn(this)
即可。
接下来,我们来看一下ReportFragment
的injectIfNeededIn()
方法。
ReportFragment--> injectIfNeededIn方法
public companion object {
private const val REPORT_FRAGMENT_TAG =
"androidx.lifecycle.LifecycleDispatcher.report_fragment_tag"
@JvmStatic
public fun injectIfNeededIn(activity: Activity) {
if (Build.VERSION.SDK_INT >= 29) {
// 29及以上,直接向Activity注册ActivityLifecycleCallbacks。
LifecycleCallbacks.registerIn(activity)
}
// 添加无布局的Fragment,如果之前已经添加,则不再添加。
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()
}
}
}
SDK >= 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())
}
}
}
SDK >= 29, Activity
会注册一个ActivityLifecycleCallbacks
监听此Activity
的生命周期变化,会在onCreate
、onStart
、onResume
方法被调用后, onPause
、onStop
、onDestroy
方法被调用前分发对应的 Event
。同一个Activity
可能会注册多个ActivityLifecycleCallbacks
,则同一个状态会调用 dispatch(Activity, Lifecycle.Event)
多次。
接下来我们来看一下,上面调用的dispatch()
的实现。
ReportFragment--> dispatch(Activity, Lifecycle.Event)方法
@JvmStatic
internal fun dispatch(activity: Activity, event: Lifecycle.Event) {
// LifecycleRegistryOwner已被弃用
if (activity is LifecycleRegistryOwner) {
activity.lifecycle.handleLifecycleEvent(event)
return
}
// ComponentActivity已经实现LifecycleOwner,并lifecycle返回的是LifecycleRegistry。
if (activity is LifecycleOwner) {
val lifecycle = (activity as LifecycleOwner).lifecycle
if (lifecycle is LifecycleRegistry) {
lifecycle.handleLifecycleEvent(event)
}
}
}
由于ComponentActivity
已经实现LifecycleOwner
,并lifecycle
返回的是LifecycleRegistry
,所以我们接下来看一下LifecycleRegistry
的handleLifecycleEvent()
方法。
LifecycleRegistry--> handleLifecycleEvent()方法
public actual open fun handleLifecycleEvent(event: Event) {
// 当enforceMainThread为true时,必须是在主线程调用,否则抛出异常
enforceMainThreadIfNeeded("handleLifecycleEvent")
moveToState(event.targetState)
}
private fun moveToState(next: State) {
if (state == next) {
// 如果要设置的状态和当前的状态相同,则直接返回
return
}
check(!(state == State.INITIALIZED && next == State.DESTROYED)) {
"State must be at least CREATED to move to $next, but was $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()
}
}
由于moveToState()
判断了同状态不处理,所以同一个事件多次调用handleLifecycleEvent
也不会有问题。
接下来,我们再来看一下sync()
方法。
LifecycleRegistry--> sync()方法
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."
)
// 只要未同步,就一直同步。不用if用while的原因,因为同步过程中状态可能改变了。
while (!isSynced) {
newEventOccurred = false
if (state < observerMap.eldest()!!.value.state) {
// 小于当前State,调用backwardPass向后。
backwardPass(lifecycleOwner)
}
val newest = observerMap.newest()
if (!newEventOccurred && newest != null && state > newest.value.state) {
// 大于当前State,调用forwardPass向前。
forwardPass(lifecycleOwner)
}
}
newEventOccurred = false
// 记录当前状态
_currentStateFlow.value = currentState
}
backwardPass()
和forwardPass()
类似,我们只看一个forwardPass()
。
LifecycleRegistry--> forwardPass()方法
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}")
// 观察者ObserverWithState分发事件,通知被Lifecycle添加的LifecycleObserver状态改变。
observer.dispatchEvent(lifecycleOwner, event)
popParentState()
}
}
}
forwardPass()
分发,用2个while
的原因,第一个while
用于遍历所有的观察者,第二个while
用于让当前观察者接收所有的事件。
SDK < 29
ReportFragment--> 生命周期方法
public open class ReportFragment() : android.app.Fragment() {
private var processListener: ActivityInitializationListener? = null
private fun dispatchCreate(listener: ActivityInitializationListener?) {
listener?.onCreate()
}
private fun dispatchStart(listener: ActivityInitializationListener?) {
listener?.onStart()
}
private fun dispatchResume(listener: ActivityInitializationListener?) {
listener?.onResume()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
dispatchCreate(processListener)
dispatch(Lifecycle.Event.ON_CREATE)
}
override fun onStart() {
super.onStart()
dispatchStart(processListener)
dispatch(Lifecycle.Event.ON_START)
}
override fun onResume() {
super.onResume()
dispatchResume(processListener)
dispatch(Lifecycle.Event.ON_RESUME)
}
override fun onPause() {
super.onPause()
dispatch(Lifecycle.Event.ON_PAUSE)
}
override fun onStop() {
super.onStop()
dispatch(Lifecycle.Event.ON_STOP)
}
override fun onDestroy() {
super.onDestroy()
dispatch(Lifecycle.Event.ON_DESTROY)
// just want to be sure that we won't leak reference to an activity
processListener = null
}
private fun dispatch(event: Lifecycle.Event) {
if (Build.VERSION.SDK_INT < 29) {
// 仅在API-29之前的版本,从ReportFragment调度事件。
// 在API-29及之后的版本,这由ReportFragment.injectIfNeededIn中添加的ActivityLifecycleCallbacks处理。
dispatch(activity, event)
}
}
public fun setProcessListener(processListener: ActivityInitializationListener?) {
this.processListener = processListener
}
}
Activity
会添加一个无布局的ReportFragment
来监听此Activity
的生命周期变化,会在对应的生命周期方法里分发对应的 Event
。同一个Activity
不会添加多个ReportFragment
,所以同一个事件不会调用多次 dispatch( Lifecycle.Event)
。
由于ReportFragment
,在SDK所有版本都有添加,而在SDK >= 29的时候是使用ActivityLifecycleCallbacks
处理的分发,所以ReportFragment
的分发需要在SDK < 29下,防止重复。
Fragment
androidx.fragment.app.Fragment--> 生命周期方法
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner,
ActivityResultCaller {
void performCreate(Bundle savedInstanceState) {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
@SuppressWarnings("ConstantConditions")
void performStart() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
...
}
@SuppressWarnings("ConstantConditions")
void performResume() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
...
}
@SuppressWarnings("ConstantConditions")
void performPause() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
...
}
void performStop() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
...
}
void performDestroy() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
...
}
androidx.fragment.app.Fragment
的实现,是直接其生命周期方法内调用的handleLifecycleEvent()
方法进行的分发。
小结
代码流程:
androidx
的Activity
,在其SDK >= 29的时候是使用ActivityLifecycleCallbacks
进行的分发,在SDK < 29的时候是使用ReportFragment
的生命周期方法进行的分发。androidx
的Fragment
,是使用androidx Fragment
的生命周期方法进行的分发。- 分发会调用
LifecycleRegistry
类handleLifecycleEvent()
方法分发,如果当前的状态和要分发的状态相同,则不处理;否则它会遍历所有的观察者,并让每个观察者依次接收到所有的事件。
总结
以上就是全面的Jetpack-Lifecycle
源码了!欢迎大家点赞、收藏,以方便您后续查看,之后会出Jetpack
其它源码系列,请及时关注。如果你有什么问题,可以在评论区留言!
最后推荐一下我的网站,开发者(Developer
)的博客(Blog
): devblog.cn ,欢迎大家来体验!