What is Coroutine Scope and how is that different from Coroutine Context?

Technology CommunityCategory: KotlinWhat is Coroutine Scope and how is that different from Coroutine Context?
VietMX Staff asked 3 years ago
  • Coroutines always execute in some context represented by a value of the CoroutineContext type, defined in the Kotlin standard library. The coroutine context is a set of various elements. The main elements are the Job of the coroutine.
  • CoroutineScope has no data on its own, it just holds a CoroutineContext. Its key role is as the implicit receiver of the block you pass to launchasync etc.
    runBlocking {
       val scope0 = this
       // scope0 is the top-level coroutine scope.
       scope0.launch {
           val scope1 = this
           // scope1 inherits its context from scope0. It replaces the Job field
           // with its own job, which is a child of the job in scope0.
           // It retains the Dispatcher field so the launched coroutine uses
           // the dispatcher created by runBlocking.
           scope1.launch {
               val scope2 = this
               // scope2 inherits from scope1
           }
       }
    }

You might say that CoroutineScope formalizes the way the CoroutineContext is inherited. You can see how the CoroutineScope mediates the inheritance of coroutine contexts. If you cancel the job in scope1, this will propagate to scope2 and will cancel the launched job as well.