Coroutines: Context and Scope

Context

Each coroutines is associated with a coroutine context with values about the runtime details for the coroutine to access if required. The Context takes the form of a map of values. The context object itself is immutable so every time a change is done, we will be creating a new context.

We can use the + operator to add elements to the context:

context + CoroutineName("download")

The coroutine context is used by different parts of the coroutine library:

  • Coroutine Name is to identify the coroutine
  • Control the dispatched thread
  • Handle uncaught exceptions

Scope

launch and async are both extension functions of the CoroutineScope

GlobalScope

  • Always available
  • Creates top-level coroutines
    • May lead to memory leaks

How do cancellation and failure bubble up from child to parent?

  • Parent coroutines will not complete until all children have completed
  • Cancelling a parent will cancel all child coroutines
  • Failure of a child will cause the parent to cancel --> cancels all sibling coroutines

Supervisor Scope

  • We can use supervisorScope to create a child coroutine but its lifecycle is detatched from the parent and siblings.
  • Failures in the child coroutine will not cancel the parent.