Search code examples
androidrx-java2rx-androidandroid-mvp

How to pass the first throwable error in rxjava2 chain calls?


I'm chaining calls for my network and local api. In case the network api failed to fetch the data, I'm catching it with my local api call. However, in situation where both the network and local api failed, I want to show the user the error from the network api and not the local. This is what I have:

remoteSource.fetchData()
            .onErrorResumeNext(e -> localSource.fetchData())
            .doOnSuccess(this::saveData)

The solution I can think of is to save the throwable caught in onErrorResumeNext in a separate variable outside the chain call. However, I'm using MVP architecture which means that this is inside the model layer. Only the last error will be caught by the presenter layer which is the error for the local source.


Solution

  • You could resume with the original error in the nested call:

    remoteSource.fetchData()
            .onErrorResumeNext(e -> 
                  localSource.fetchData()
                  .onErrorResumeNext(f -> Single.error(e))
            )
            .doOnSuccess(this::saveData)