Kotlinx.coroutines: Error Flow builder

Created on 23 Sep 2019  路  3Comments  路  Source: Kotlin/kotlinx.coroutines

RxJava has Observable.error(Throwable) and Flowable.error(Throwable). Would it make sense or be useful to have a similar Flow builder for easily creating a Flow that errors?

Something like the following:

public fun <T> errorFlow(error: Throwable): Flow<T>

This is useful for testing purposes when you wish to test a dependency that exposes a Flow that may throw an exception.

It is pretty straightforward to implement such a utility locally using the flow { } builder but figured it would be useful to have an official implementation from the library.

question

All 3 comments

Why is it useful? Can you give a motivating example? This is so easy to write with flow:

flow { throw error }

We need a really strong and frequent use to introduce a separate operator for that.

That's fair. I guess it really doesn't get any more concise than that. 馃檪

In RxJava, I can see Observable.error() being useful in operators like flatMap where conditionally you may want to terminate with a custom error based on a specific emission.

My usages of Observable.error() have really only been frequent in tests.
Example:

val error = Exception()
given(fooRepository.observeFoo()).willReturn(Observable.error(error))

With Flow, I guess it would be

val error = Exception()
given(fooRepository.observeFoo()).willReturn(flow { throw error })

vs.

val error = Exception()
given(fooRepository.observeFoo()).willReturn(errorFlow(error))

IMO, not a big difference. We don't need to introduce such an operator. The plus is that we don't have to bikeshed a name (errorFlow name is not consistent with Kotlin coroutines nomenclature).

Was this page helpful?
0 / 5 - 0 ratings