RxJava / RxBinding: how to handle errors in RxView

I am using RxJava and RxBindings to view in android. Below is an example of what I am doing.

RxView.clicks(btMyButton).flatMap(btn -> { // another observable which can throw onError. return Observable.error(null); }).subscribe(object -> { Log.d("CLICK", "button clicked"); }, error -> { Log.d("CLICK", "ERROR"); }); 

when I click on MyButton, I use flatMap to return another observable, which is a network call, and may return success or error. when it returns an error, I process it in the error block. but I cannot press the button again.

How can I handle the error and still be able to click the button again?

+6
source share
3 answers

GreyBeardedGeek is in place. To clearly indicate one of your options, you can use .materialize() :

 RxView.clicks(btMyButton).flatMap(btn -> { if (ok) return someObservable.materialize(); else return Observable.error(new MyException()).materialize(); }).subscribe(notification -> { if (notification.hasValue()) Log.d("CLICK", "button clicked"); else if (notification.isOnError()) Log.d("CLICK", "ERROR"); }); 

By the way, do not pass null to Observable.error() .

+7
source

I am new to RxJava but have run into this problem myself.

The problem is that, by definition, Observable stops emitting values ​​when the error () method is called.

As far as I can tell, you have two options:

  • change the Observable, which makes the network call in such a way that when an error occurs, an exception is not thrown, but you return a value indicating the error. Thus, the Observable error () method will not be called when a network error occurs.

  • Look at using Observable.onErrorResumeNext to override the completion of Observable when calling the error () function. See Best Practice for onError Handling and Continuous Handling

+4
source

I use an approach similar to that already described:

 RxView.clicks(btMyButton) .flatMap(btn -> { // another observable which can throw onError. return Observable.error(null) .doOnError(error -> { //handle error }) .onErrorResumeNext(Observable.empty());//prevent observable from terminating }) .subscribe(object -> { Log.d("CLICK", "button clicked");//here no errors should occur }); 

I have a short article that describes this approach.

+1
source

All Articles