CoroutineScope vs GlobalScope

THis is a straightforward question to ask, although possibly not to answer. In those cases where I am launching a top level coroutine, and don’t (for whatever reason) have a containing scope, I seem to have two options:

CoroutineScope(ContextAwareInterceptor(executor.asCoroutineDispatcher(), context)).launch {
...do some async work
}

or

GlobalScope.launch(ContextAwareInterceptor(executor.asCoroutineDispatcher(), context)) {
...    
}

Are there any critical disticntions between these two solutions? The documentation suggests to avoid use of GlobalScope for launch or async, but what rewards am I gaining / risks am I taking by using the first approach?

If a coroutine does not have a scope, then I consider the GlobalScope a good choice.

Using the first block allows you to start multiple coroutine in that scope and dispose these when required, you can find this solution in the last example on this page Kotlin Coroutines patterns & anti-patterns | by Dmytro Danylyk | ProAndroidDev

1 Like