Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resume flow after exception

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?

like image 853
gookman Avatar asked Feb 03 '20 12:02

gookman


1 Answers

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()

    }
like image 111
gildor Avatar answered Sep 19 '22 14:09

gildor