'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 1:[1]

You can create an method that will receive this error normally, something like

private void onError(Throwable error) {
// do whatever you want with your error
}

...
.onErrorReturn( error -> onError(error) )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Massita