Do we need multiple coroutinescopes in an android ...
# coroutines
r
Do we need multiple coroutinescopes in an android app? If I provide a
CoroutineScope
as a dependency which every module can access then we can launch different coroutines using this one scope? Each child coroutine can then have its own
CoroutineExceptionHandler
as well. Is my understanding correct?
s
One benefit of using multiple scopes is to ensure that work gets cancelled when it's no longer needed. For example, having a scope for each activity means that coroutines launched by that activity get cancelled when the activity is cleaned up.
In a way this is the same question as "why not just use GlobalScope for everything", which is answered nicely here: https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc
And to answer your question about exception handlers: unfortunately, it won't work the way you describe.
all children coroutines (coroutines created in the context of another Job) delegate handling of their exceptions to their parent coroutine, which also delegates to the parent, and so on until the root, so the CoroutineExceptionHandler installed in their context is never used.
https://kotlinlang.org/docs/exception-handling.html#coroutineexceptionhandler
r
even if our child coroutine has a
SupervisorJob
context?
s
You're right, coroutines in supervisor scope are an exception to that rule. The docs I linked to call that out explicitly.
coroutines launched directly inside the supervisorScope do use the CoroutineExceptionHandler that is installed in their scope in the same way as root coroutines do
https://kotlinlang.org/docs/exception-handling.html#exceptions-in-supervised-coroutines
r
I understood how having different scopes can be helpful. By cancelling the scope during cleanup all coroutines launched by this scope get cancelled. But for the sake of discussion.. we can also keep track of coroutines launched using the single scope and make sure to cancel them once they are no longer required? I understand the scope itself is not cancelled as this behaves like an "application scope"
s
we can also keep track of coroutines launched using the single scope and make sure to cancel them once they are no longer required?
That's touched on by Roman in his article about GlobalScope, which I linked to above. He basically says that manually keeping track of all your coroutines would work, but it would get quite complicated, and scopes make it much simpler.
👍 1