https://kotlinlang.org logo
#coroutines
Title
# coroutines
u

윤동환

10/15/2023, 11:41 PM
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

myanmarking

10/16/2023, 12:29 PM
without a small sample there little we can you advise you about.
u

윤동환

10/16/2023, 1:01 PM
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

myanmarking

10/16/2023, 2:32 PM
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

윤동환

10/16/2023, 10:41 PM
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.