I have the following code:
val channel = BroadcastChannel<Event>(10)
fun setup() {
scope.launch {
channel.asFlow().
.flatMapLatest { fetchSomeData() }
.catch { emit(DefaultData()) }
.onEach { handleData() }
.collect()
}
}
fun load() {
channel.offer(Event.Load)
}
In case fetchSomeData
fails with an exception it will be caught by catch
and some default data is passed on. The problem is that the flow itself gets canceled and is being removed from the subscribers of the channel. This means that any new events offered to the channel will be ignored since there are no longer any subscribers.
Is there a way to make sure the flow does not get cancelled in case of an exception?
You should catch exception of fetchSomeData(), so move catch
from main flow to fetchSomeData():
scope.launch {
channel.asFlow().
.flatMapLatest { fetchSomeData().catch { emit(DefaultData()} }
.onEach { handleData() }
.collect()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With