Search code examples
javaandroidrx-javarx-java2

How to handle errors in an Observable chain conditionally?


I am using onErrorReturn to emit a particular item rather than invoking onError if the observable encounters an error:

Observable<String> observable = getObservableSource();
observable.onErrorReturn(error -> "All Good!")
          .subscribeOn(Schedulers.io())
          .observeOn(Schedulers.trampoline())
          .subscribe(item -> onNextAction(),
              error -> onErrorAction()
          );

This works fine, but I want to consume the error in onErrorReturn only if certain conditions are met. Just like rethrowing an exception from inside a catch block.

Something like:

onErrorReturn(error -> {
    if (condition) {
        return "All Good!";
    } else {
        // Don't consume error. What to do here?
        throw error; // This gives error [Unhandled Exception: java.lang.Throwable]
    }
});

Is there a way to propagate the error down the observable chain from inside onErrorReturn as if onErrorReturn was never there?


Solution

  • Using onErrorResumeNext I guess you can achieve what you want

    observable.onErrorResumeNext(error -> {
                  if(errorOk)
                      return Observable.just(ok)
                  else
                      return Observable.error(error)
              })
              .subscribeOn(Schedulers.io())
              .observeOn(Schedulers.trampoline())
              .subscribe(item -> onNextAction(),
                  error -> onErrorAction()
              );