Why Android lifecycleScope can be automatically cancelled

1.2k Views Asked by At

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!

1

There are 1 best solutions below

2
darshan On

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.