Job is the primary mechanism for controlling cancellation behavior of co-routines.
Job - provides another avenue of stopping work other than traditional exception flow. Separate cancellation mechanism that is not as apparent as typical exceptions, where failed co-routine cancel’s all co-routines that are related to it through Job hierarchy. (Note: Supervisor-Job is exception)
Exception/Cancellation Behavior with Regular Job
In ALL scopes that use Regular:
- Uncaught, non-cancellation exception → Cancels Siblings + Propagates recursively through parent Job hierarchy, with each parent shutting down its children, Effectively shutting down the entire hierarchy up to the top most Job (or up to where you caught exception at error boundary).
- Cancels siblings: functions-suspension-point in sibling functions will throw CancellationException
- Propagates to parent: Parent scope will rethrow the original exception that was thrown in co-routine.
Highlight
Job - provide another avenue of stopping work other than traditional exceptions. Separate cancellation mechanism that is not as apparent as typical exception flow, where failed co-routine cancel’s all co-routines that are related to it through Job hierarchy.
- Each coroutine has its own Job instance.
- Each Job instance is tied to it’s parent job (if it has a parent Job). This tie in enables cancellation behavior.
Example
If regular
Job()were used. If Coroutine#6 throws non-CancellationException exception the entire hierarchy is gonig to be cancelled and Coroutine#1 will rethrow the exception that Coroutine#6 threw.
{max-width: 500px, display: block, margin: 0 auto, border: 5px solid black}
Creating Error Boundary
- Look at scope-function-error-boundary to create error/ boundaries which allows us to try/catch exceptions stopping them from going higher up.
Gotchas
Link to originalCancellation Gotchas (With Regular Job)
Link to original
- ⚠️ Firstly, make sure to understand intended ExceptionCancellationBehavior ⚠️.
- evil-example-swallowing-cancel-exception
- exceptions-from-async-under-coroutineScope-go-to-parent-and-not-await
- cancel-call-does-not-stop-right-away
- join
{max-width: 500px, display: block, margin: 0 auto, border: 5px solid black}