Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 922
Abhishek Jain Avatar asked Apr 09 '18 19:04

Abhishek Jain


1 Answers

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()
          );
like image 191
Samuel Eminet Avatar answered Sep 27 '22 18:09

Samuel Eminet