Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava chaining observables and error handling(custom exception propagation)

Tags:

rx-java

I have 5 Observables that're chained with flatMap. In case first four Observables produce an Exception I want to propagate a different type of Exception to the fifth.

How is it achieved?

Thanks.

P.S. I've come up with this yet untested solution:

flatMap(
        // onNext
        new Func1<BoolResponse, Observable<?>>() {
            @Override
            public Observable<?> call(BoolResponse boolResponse) {
                return request;
            }
        },
        // onError
        new Func1<Throwable, Observable<?>>() {
            @Override
            public Observable<?> call(Throwable throwable) {
                return Observable.error(new SomethingWentWrong());
            }
        },
        // onCompleted
        new Func0<Observable<?>>() {
            @Override
            public Observable<?> call() {
                return request;
            }
});

Do you think it's OK?

like image 258
midnight Avatar asked Oct 07 '14 09:10

midnight


1 Answers

What you're looking for is onErrorResumeNext which will allow you to catch any Throwable emitted from the source and allows you to either resume with a new Observable or another Observable which would emit a different Throwable.

    ...
    .flatMap(...)
    .flatMap(...)
    .onErrorResumeNext(new Func1<Throwable, Observable<?>>() {
        @Override
        public Observable<?> call(Throwable throwable) {
            // Here simply return an Observable which will emit the Throwable of your liking
            return Observable.error(new Throwable(...));
        }
    })
    .flatMap(...);

Keep in mind that flatMap is an operator to handle your stream of data but it will not allow you to handle onError has in your code example. You can handle the error in your Observer's onError callback where you subscribe to the stream.

like image 136
Miguel Avatar answered Sep 22 '22 11:09

Miguel