kevin.cianfarini
05/18/2023, 8:12 PMthrow CancellationException
?
eg:
flow { /* do some stuff */ }.catch { e ->
when (e) {
is MySpecialException -> {
triggerMySideEffect()
throw CancellationException(e)
}
else -> throw e
}
}
stojan
05/19/2023, 5:49 PMkevin.cianfarini
05/19/2023, 5:55 PMMySpecialException
into a CancellationException
. I ended up with this:
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)
}
}
}