Search code examples
javakotlinrx-javarx-java2reactivex

Catch an error and return a new type in RxJava2


I have a stream:

val symbols: Single<List<Symbol>>

Now I want to transform the stream into a UI State with map():

private fun cool(): Single<SymbolContract.State> =
    symbols.map { SymbolContract.State.Symbols(it) }

What I want to do is catch an error on the upstream symbols single, so that I can catch any errors and then return SymbolContract.State.GeneralError().

I want something like a onErrorMap() or something. Unfortunately, putting onErrorResumeItem on symbols doesn't work because it needs to return a List<Symbol>.

I can think of a few ugly ways to do this, but what's the cleanest?


Solution

  • Found a clean answer:

    private fun symbols(): Single<SymbolContract.State> =
           symbols.map<SymbolContract.State> { SymbolContract.State.Symbols(it) }
                .onErrorReturnItem(SymbolContract.State.Error(SymbolContract.State.Error.Type.Network))
    

    The onErrorReturnItem has to come after the map, and the map needs explicit type parameters.