简体   繁体   中英

Why Android lifecycleScope can be automatically cancelled

When reading this post about lifecycle-aware CoroutineScope, I read the following:

Every Lifecycle comes with a LifecycleScope, which lets you launch coroutines that are automatically cancelled once the Lifecycle reaches the DESTROYED state.

I was reading the source code in lifecycle-runtime-ktx.aar , and was trying to figure out how come the lifecycleScope (accessed within a Fragment or an Activity) can be cancelled when it gets DESTROYED.

Can anyone please point me out why lifecycleScope can be automatically cancelled? And where is the source code about this part. Thanks!

Activity & Fragment internally use the LifecycleCoroutineScope which is then hooked to the Lifecycle of the component via lifecycle.addObserver .

If you check the LifecycleCoroutineScopeImpl ,
you'll see this:

if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
    coroutineContext.cancel()
}

and

if (lifecycle.currentState <= Lifecycle.State.DESTROYED) {
    lifecycle.removeObserver(this)
    coroutineContext.cancel()
}

In short,
An observer is added to the component & if the lifecycle.currentState falls below Lifecycle.State.DESTROYED then the running coroutines are cancelled automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM