Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw error in onNext() with RxJava

Tags:

java

rx-java

.subscribe(
    new Action1<Response>() {
        @Override
        public void call(Response response) {
            if (response.isSuccess())
            //handle success
            else
            //throw an Throwable(reponse.getMessage())
        }
    },
    new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            //handle Throwable throw from onNext();
        }
    }
);

I don't wanna handle (!response.isSuccess()) in onNext(). How can I throw it to onError() and handle with other throwable together?

like image 542
Rox Avatar asked Oct 19 '16 10:10

Rox


People also ask

How does Java handle Rx errors?

Here, in the above code we see as soon as we get an exception in map operator and then we directly goto onError and the onNext doesn't get called or even onComplete. So, to handle the error in cases like this we use different operators and it will not move to onError directly. Let us understand them one by one.

Which of the following happens when an error occurs using RxJava?

RxJava Error Handling That means that after error happened stream is basically finished and no more events can come through it. If Consumer didn't handle error in Observer callback, then that error is sent to a global error handler (which in case of Android crashes the app by default).

When the onNext () method of the subscriber is called?

After a Subscriber calls an Observable 's subscribe method, the Observable calls the Subscriber's Observer. onNext(T) method to emit items. A well-behaved Observable will call a Subscriber's Observer. onCompleted() method exactly once or the Subscriber's Observer.

What is Completable RxJava?

Single and Completable are new types introduced exclusively at RxJava that represent reduced types of Observable , that have more concise API. Single represent Observable that emit single value or error. Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.


1 Answers

If FailureException extends RuntimeException, then

.doOnNext(response -> {
  if(!response.isSuccess())
    throw new FailureException(response.getMessage());
})
.subscribe(
    item  -> { /* handle success */ },
    error -> { /* handle failure */ }
);

This works best if you throw the exception as early as possible, as then you can do retries, alternative responses etc. easily.

like image 100
Tassos Bassoukos Avatar answered Oct 06 '22 10:10

Tassos Bassoukos