hello I do not know if this is intended to work th...
# announcements
o
hello I do not know if this is intended to work this way but I’m merging two flows and then collecting the result flow and catching the exceptions on it, but I just found that if one of the flows has an exception then the merge does not emit the value of the other flow nor the emitted value in the catch clause like:
Copy code
val flow1 = flow<Int> {
    emit(1)
}
val flow2 = flow<Int> {
    throw IOException()
}
merge(flow1, flow2).onEach {
    print(it.toString() + "\n")
}.catch {
    emit(3)
}.launchIn(CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>))
Do I have to catch the flows before merging them or there is something wrong in the example ?
z
If you want other flows to continue to emit when one of them fails, then yes you'd need to catch each flow before merging them. Failure is a terminal event, so if the failure makes it to the merge, the flow that merge returns will fail, ie terminated.
As for why the failure is making it to the merge before the emission from the first flow, I'm not sure if that ordering is expected or left undefined by the merge operator contract, but it seems risky to rely too much in that implicit ordering anyway.
o
Ok thank you very much @Zach Klippenstein (he/him) [MOD] for the explanation. I would expect be able to use the catch in the merge because for example I’m doing something in a layer that performs the merge and then other layer receives the flow generated and I want to be able to handle the exception in the other layer rather than the origin that in my case is just re throwing
z
Think of it in terms of error propagation and stream termination. The
merge
operator will forward items from all its inputs, but if one of them fails, it has to propagate that error downstream. And the Flow contract says that once a stream has failed (the collector receives an exception), then it can’t emit any more. So if the merge operator propagates the error downstream, that means the downstream has to be considered failed, and can’t emit anything else.
👍 1