https://kotlinlang.org logo
#coroutines
Title
# coroutines
f

Florian

10/29/2020, 10:54 AM
To avoid using GlobalScope in my small project, I created this application scope provided by Dagger:
Copy code
@ApplicationScope
@Provides
@Singleton
fun provideApplicationScope() = CoroutineScope(SupervisorJob())
Should I also inject the dispatcher that is used with this scope, and why?
g

gildor

10/29/2020, 12:20 PM
it will use Default distpacher, which is probably fine default
f

Florian

10/29/2020, 3:25 PM
makes sense, thanks
if I don't do any configuration on the scope, is there still any benefit over GlobalScope? (I have written that article by Manuel Vivo)
t

travis

10/29/2020, 10:31 PM
As you have your
CoroutineScope
written, it would exhibit different behavior than
GlobalScope
since you're using
SupervisorJob
. You can additionally have an exception handler (and other customizations). Without those customizations, it would essentially be the same as
GlobalScope
. I think that comes down to preference at that point. I personally think
GlobalScope
is a good choice if you want that specific behavior (i.e. on Android crashing app if an uncaught exception is thrown) as the
GlobalScope
in your code makes it explicit the behavior that you'll have with it. Depending on your architecture though, it might make more sense to use a custom scope that you inject, to make swapping it out easier in unit tests. It probably comes down to how you want your structured concurrency to be organized (what scope you want to be the parent for Coroutines you'll be launching).
g

gildor

10/30/2020, 1:29 AM
Though, there one more feature of own scope comparing to GlobalScope, you can cancel it or all running childs of it. It can be good (if you have use case for it) and it can be bad (anyone can inject and cancel it)
👍 1
f

Florian

10/30/2020, 9:41 AM
Thank you for the explanations!
11 Views