I have a Flow that can potentially throw a specifi...
# coroutines
k
I have a Flow that can potentially throw a specific exception I want to handle and trigger a side effect on. When that exception is caught, and the side effect is triggered, the flow returned from the catch function is no longer valid. Is the correct way to cancel that flow to just to
throw CancellationException
? eg:
Copy code
flow { /* do some stuff */ }.catch { e -> 
  when (e) {
    is MySpecialException -> {
      triggerMySideEffect()
      throw CancellationException(e)
    }
    else -> throw e
  }
}
s
No need for special handling of Cancellation exception, catch already takes care of that
k
I am hoping to essentially coerce
MySpecialException
into a
CancellationException
. I ended up with this:
Copy code
flow {
        // Introduce a `coroutineScope` here to that we have a mechanism that allows
        // flow cancellation. This could alternatively be done by canceling the
        // `currentCoroutineContext`, but we opt to create an intermediary scope here
        // instead to ensure we're not accidentally canceling parent jobs that survive
        // child cancellation, eg: `SupervisorJob`.
        coroutineScope {
            try {
                // Try to collect the flow and emit it downstream.
                myOtherFlow().collect { emit(it) }
            } catch (e: MySpecialException) {
                triggerMySideEffect()
                cancel(message = "That special case happened!", cause = e)
            }
        }
    }