Propagate exceptions downstream with shared flow similar to `PublishSubject.onError` from RxJava

Viewed 293

In kotlin SharedFlow is a hot observable where we can emit certain values, so I have declared:

private val _state: MutableSharedFlow<State> =  MutableSharedFlow()
val state = _state.asSharedFlow()

With this in place I can emit states in other places of the class by using tryEmit(State()). I'm not sure though what's the right way to achieve emitting error / throwing exception in that hot shared flow. With RxJava it was pretty easy to do with PublishSubject and onError(RuntimeException()) but with shared flow it's different. I couldn't find any relevant API to do that (propagate an error) link. The only thing I found is this huge thread and precisely this comment that gives me a hint:

state.map {
    when (it) {
        is Success -> it.value
        is Error -> throw it.exception
    }             
}

But this looks more like taking a step back.

Another option is to forget about throwing exceptions and relay on error codes, but for consistency with other parts of my app, I wanted to propagate errors in this flow.

What's the right way of doing that with SharedFlow to achieve equivalent of RxJava onError?

0 Answers
Related