CoroutineContext is a map of elements that define a coroutine’s behavior, as well as carry supporting information.
Diagram
Coroutine Diagram
graph TD; A[coroutineContext] -->|Has a| B("Job") A -->|Has a| C[Dispatcher] A -->|Has a| CoroutineExceptionHandler B -->|Parent of| J1[Child Job 1] B -->|Parent of| J2[Child Job 2] B -->|Parent of| J3[Child Job 3] J1 -->|Manages| D1[Coroutine 1] J2 -->|Manages| D2[Coroutine 2] J3 -->|Manages| D3[Coroutine 3] D1 -->|Runs| E1[Task 1] D2 -->|Runs| E2[Task 2] D3 -->|Runs| E3[Task 3] classDef blue fill:#3b82f6,stroke:#ffffff,stroke-width:2px; classDef green fill:#10b981,stroke:#ffffff,stroke-width:2px; classDef red fill:#ef4444,stroke:#ffffff,stroke-width:2px; class A blue; class B green; class D1,D2,D3 red;References
Link to original
Behavioral elements (affect how the coroutine runs):
- Job — controls the lifecycle of the coroutine.
- Dispatcher — defines the thread/thread-pool the work will be dispatched to.
- CoroutineExceptionHandler — handles uncaught exceptions.
Supporting information elements
CoroutineName— Adds a name to the coroutine (useful for debugging).- custom-CoroutineContextElement: custom elements that can be added to the context. Such as adding request id.