Search code examples
androidkotlinkotlin-coroutines

Difference between CoroutineScope(Dispatchers.IO + Job()) and CoroutineScope(Dispatchers.IO) + Job()


I wonder what the difference is between these 2 ways of creating a scope?

val scope1 = CoroutineScope(Dispatchers.IO + Job()) 

vs

val scope2 = CoroutineScope(Dispatchers.IO) + Job()

I noticed that both create a CoroutineScope. Is there any difference between these two approaches?


Solution

  • It is effectively the same.

    Coroutine context (so e.g. Dispatchers.IO) and coroutine scope are pretty much the same thing. They have a different meaning in the code: context is a kind of map and scope is a wrapper on top of this map, which provides various kinds of functionality. However, scope always wraps a context and adding new elements to the scope is the same as adding them to the context.

    For user convenience, coroutines framework provides functions/extensions that allow to add context elements both to a context and to a scope. It does a similar thing. For example, when we do CoroutineScope(Dispatchers.IO) + Job(), then we call the operator:

    public operator fun CoroutineScope.plus(context: CoroutineContext): CoroutineScope =
        ContextScope(coroutineContext + context)
    

    It unwraps the context associated with the scope (coroutineContext), adds a new context element, then it creates a new scope using the new context. So this is effectively the same as CoroutineScope(Dispatchers.IO + Job()).