RxJava / RxAndroid: continue range loop after error

543 views Asked by At

Here is my sample code with the result:

Observable.range(0, 10)
    .flatMap(actNumber -> {
        if (actNumber == 3) {
            return Observable.error(new Throwable("This is an error"));
        }
        return Observable.just(actNumber);
        })
    .onErrorReturnItem(-1)
    .subscribe(new Consumer<Integer>() {
        @Override
        public void accept(Integer number) throws Exception {
            Logs.d("number -> " + number);
        }
    }, new Consumer<Throwable>() {
         @Override
         public void accept(Throwable throwable) throws Exception {
             Log.d("RX", "Error: " + throwable.toString());
         }
    });

0, 1, 2, -1

Is it ok, but how can I set it that for this result?

0, 1, 2, -1, 4, 5, 6, 7, 8, 9

Thank you, Robert

1

There are 1 answers

0
dsrees On

According to the Observable contract, once an Observable emits onError or onCompleted, then no more elements will be emitted by the Observable signal. The problem that you are having is that you are returning Observable.error() if the number is 3 which will emit an onError to your Consumer and then terminate the signal.

By the contract, you cannot continue a signal after it errors. However what you can do is catch and recover from the error and begin to return a new Observable signal. The documentation for the operator can be found here.

Here is an example

Observable
    .error(new Throwable("error"))
    .catchErrorResumeNext(Observable.range(3, 10))

(Note: I did not test this code, but it should point you in the right