Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava FlatMap: How to skip errors?

Tags:

java

rx-java

In chain obs1.flatmap(x -> obs2()).subscribe(sub) if obs2 produces an error, it causes immediate calling onError on sub. This is as documented:

Note that if any of the individual Observables mapped to the items from the source Observable by flatMap aborts by invoking onError, the Observable produced by flatMap will itself immediately abort and invoke onError.

But is it possible to ignore obs2 errors and make obs1 continue emitting?

like image 943
Alexey Avatar asked Feb 10 '17 14:02

Alexey


2 Answers

Rx provide some operators to deals with errors. Just create a third Observable from obs2 that doesn't propagate error.

Observable<YourType> obs3 = obs2.onErrorResumeNext(Observable.<YourType>empty());
obs1.flatmap(x -> obs3)
like image 151
Geoffrey Marizy Avatar answered Oct 23 '22 14:10

Geoffrey Marizy


.onErrorResumeNext - you can use this to try to handle it differently, this way you will pass the previously emitted value, which when handled produced an error to another observable where you can try another approach. Or handle the error case.

.onErrorReturn - If it is ok for you, just return some default value and ignore the error.

like image 35
Andrej Jurkin Avatar answered Oct 23 '22 15:10

Andrej Jurkin