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).

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.

img{max-width: 500px, display: block, margin: 0 auto, border: 5px solid black}

Creating Error Boundary

Gotchas

Cancellation Gotchas (With Regular Job)

Link to original

Link to original