Is it necessary to call scope.cancel in the onDest...
# coroutines
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?
basically does
. 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.
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?
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
, which is a suspending function, will be cancelled if it is still waiting as soon its scope is cancelled.
Without a crash right
No crash… cancellation does not cause a crash
Look for “Structured Concurrency” in kotlin. Also, I wrote an article about it:
Good to know, thanks Anton