kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Generalize coroutineScope/supervisorScope with user-specified strategy

Open elizarov opened this issue 6 years ago • 0 comments
trafficstars

The difference between coroutineScope and supervisorScope can be narrowed down to the strategy of dealing with children exceptions. When a child coroutine fails with exception, it can be either propagated to all the sibling coroutines and cause the whole scope to be cancelled or it can be handled by the child itself (for async coroutines it means just stroing exception in the resulting Deferred and for launched coroutine it means delivering it to the CoroutineExceptionHandler).

Currently we have two public variants of this child exception handling strategy:

  • supervisorScope -- all exceptions are handled (do not propagate).
  • coroutineScope (this is also a default for all the scopes created by all the other coroutine builders) -- all descendants of CancellationException are handled, all other exceptions are propagated. The rationale for this behavior to be a default, is that it allows a parent coroutine to cancel any of its children using job.cancel() without cancelling itself.

However, sometimes a different strategy is preferable, especially when writing the code that accepts 3rd party code in its callbacks which might was to cancel the current job or can simply throw a CancellationException. Originally, it was an issue with some concurrentFlow operators that need to ensure that all concurrent flows are cancelled when one of them is cancelled. An internal flowScope function was defined that propagetes all exceptions but the exception which is internally used by size-limiting operators (like take) to abort the flow. There is currently no public API to define a function like a flowScope.

The general idea is that this exception handling strategy can become an optional parameter to coroutineScope, so that a supervisorScope simply becomes a shorthand to coroutineScope call with "handle everything" strategy. However, we don't have a good name for this strategy yet.

elizarov avatar Aug 04 '19 08:08 elizarov