Mr.Eddart
Mr.Eddart

Reputation: 10273

RxJava: catch exception properly

I am trying to perform some IO operation in the Schedulers IO thread, and if an exception is thrown, I want to show some Toast to the user.

For this I use the following code:

Observable.interval(0, 15, TimeUnit.SECONDS)
            .observeOn(Schedulers.io())
            .doOnNext(event -> new Repository().inputOutput(MainActivity.this);)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> 
                    Toast.makeText(MainActivity.this, "Error message", Toast.LENGTH_SHORT).show())
            .subscribe();

When an exception is thrown on method "inputOutput", I expect the Throwable to be catched in the "doOnError" consumer, but it doesn't happen and the exception is thrown to the surrounding code.

What am I doint wrong? Thank you very much!

Upvotes: 1

Views: 2050

Answers (1)

600
600

Reputation: 82

Should looks like this :

Observable.interval(0, 15, TimeUnit.SECONDS)
              .flatMap(event -> new Repository().inputOutput(MainActivity.this);)        
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({your onNext/onComplete handler}, throwable -> 
                    Toast.makeText(MainActivity.this, "Error message", Toast.LENGTH_SHORT).show()));

Upvotes: 2

Related Questions