Coroutines: Context and Scope
Each coroutines is associated with a coroutine context with values about the runtime details for the coroutine to access if required.
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
async are both extension functions of the CoroutineScope
- 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
- We can use
supervisorScopeto create a child coroutine but its lifecycle is detatched from the parent and siblings.
- Failures in the child coroutine will not cancel the parent.