public val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope
get() = lifecycle.coroutineScope
其中LifecycleOwner.lifecycleScope返回的是LifecycleOwner的getLifecycle().coroutineScope, 而coroutineScope又是Lifecycle的扩展属性:
public val Lifecycle.coroutineScope: LifecycleCoroutineScope
get() {
while (true) {
val existing = mInternalScopeRef.get() as LifecycleCoroutineScopeImpl?
if (existing != null) {
return existing
}
val newScope = LifecycleCoroutineScopeImpl(
this,
SupervisorJob() + Dispatchers.Main.immediate
)
if (mInternalScopeRef.compareAndSet(null, newScope)) {
newScope.register()
return newScope
}
}
}
lifecycleScope返回的是一个LifecycleCoroutineScopeImpl对象,而LifecycleCoroutineScope则是一个使用 SupervisorJob() + Dispatchers.Main.immediate 作为协程上下文的CoroutineScope对象。
internal class LifecycleCoroutineScopeImpl(
override val lifecycle: Lifecycle,
override val coroutineContext: CoroutineContext
) : LifecycleCoroutineScope(), LifecycleEventObserver {
init {
if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
coroutineContext.cancel()
}
}
fun register() {
launch(Dispatchers.Main.immediate) {
if (lifecycle.currentState >= Lifecycle.State.INITIALIZED) {
lifecycle.addObserver(this@LifecycleCoroutineScopeImpl)
} else {
coroutineContext.cancel()
}
}
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (lifecycle.currentState <= Lifecycle.State.DESTROYED) {
lifecycle.removeObserver(this)
coroutineContext.cancel()
}
}
}
public enum State {
DESTROYED, // 0
INITIALIZED, // 1
CREATED, // 2
STARTED, // 3
RESUMED; // 4
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
而 Activity和Fragment都实现了LifecycleOwner接口(可以通过getLifecycle()获取到Lifecycle的实例对象),在Activity和Fragment内部都实现了Lifecycle机制,Activity和Fragment对象中都有一个Lifecycle的实例对象LifecycleRegistry,当Activity和Fragment生命周期函数变化时,会触发持有的Lifecycle实例对象的相关方法,改变对应的状态值,进而调用到其持有的观察者回调接口,即上面的LifecycleCoroutineScopeImpl对象里的onStateChanged()方法。并在其中判断如果是DESTROYED 状态就调用协程上下文的cancel方法取消协程。
public abstract class LifecycleCoroutineScope internal constructor() : CoroutineScope {
internal abstract val lifecycle: Lifecycle
public fun launchWhenCreated(block: suspend CoroutineScope.() -> Unit): Job = launch {
lifecycle.whenCreated(block)
}
public fun launchWhenStarted(block: suspend CoroutineScope.() -> Unit): Job = launch {
lifecycle.whenStarted(block)
}
public fun launchWhenResumed(block: suspend CoroutineScope.() -> Unit): Job = launch {
lifecycle.whenResumed(block)
}
}
内部其实是一个DispatchQueue封装了ArrayDeque队列。判断生命周期如果小于当前可执行的生命周期则加入队列,等到对应生命周期来到在取出执行。
val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
throwable.printStackTrace()
}
lifecycleScope.launch(coroutineExceptionHandler) {
lifecycle.whenCreated {
// TODO:
}
}