Is it necessary to call scope.cancel in the onDest...
# coroutines
p
Is it necessary to call scope.cancel in the onDestroy() without using job? For instance, one method that is using launch{} without assign it to a job? I guess is for avoid leaks, right? If I'm injecting mainScope() and a Dispatcher is necessary that on onDestroy cancel both?
s
CoroutineScope.cancel()
basically does
this.coroutineContext[Job]?.cancel()
. This will cause the scope’s top-Job, tied to the scope’s top coroutine, to be cancelled. No need to use Job itself. Don’t cancel a dispatcher. Just cancel the scope.
p
So, this is to avoid leaks then? Because if for instance I start a launch that has a delay of 5000 and then close the activity before the job is done it will stay running the coroutine anyways right?
s
Yup. Cancelling the (top) scope prevents leakage of background tasks. Cancelling a scope will cause all its suspending coroutines to be cancelled. I.e. if any part of the code inside a scope’s coroutine (and the coroutines children, etc) is suspending, they will be cancelled.
👍 1
This means the
delay(….)
, which is a suspending function, will be cancelled if it is still waiting as soon its scope is cancelled.
p
Without a crash right
s
No crash… cancellation does not cause a crash
Look for “Structured Concurrency” in kotlin. Also, I wrote an article about it: https://medium.com/swlh/how-can-we-use-coroutinescopes-in-kotlin-2210695f0e89
p
Good to know, thanks Anton