what is the best way of flow’s exception handling ...
# coroutines
u
what is the best way of flow’s exception handling for infinite data emit and infinite data consuming? I’m using SharedFlow in event bus patterns and data emitting to this bus and data consuming from this bus never be broken. So that i used try catch blocks on flow emit code and flow onEach block. Is it good pattern using try catch block at emitting data end consuming data and there are another choices better than try catch?
m
without a small sample there little we can you advise you about.
u
some code snippets here
Copy code
class EventBus {
    private val scope = CoroutineScope(SuperviserJob))
    private val _event = MutableSharedFlow<Int>()
    val event = _event.asSharedFlow()

    init {
        scope.launch {
            var no = 0
            while (true) {
                no++ // simulate io bound task. in real, it can throw a exception.
                _event.emit(no)
                delay(1000L)
            }
        }
    }
}

suspend fun consume() {
    val bus = EventBus()
    bus.event
        .onEach { no -> // do something IO bound task that can throw exception }
        .launchIn(CoroutineScope(SupervisorJob()))
}
m
these are two different problems
the producer can throw, the consumer can also throw
try catch in both.
using catch flow block in the consumer side won’t help you, unless in that case u can just skip the failure
u
Using catch operation helps handling error while consuming data, but just once. After catch operator called, the consuming upper flow is cancelled
Then should use classical way surround try catch block on throwable code.