To avoid using GlobalScope in my small project, I...
# coroutines
f
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
it will use Default distpacher, which is probably fine default
f
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
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
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
Thank you for the explanations!