Android rxjava: how to recover from errors in the flatmap operator
I have an EditText in which the user enters a search query. When the user types, I want to perform an instant search on the server
I try to do this using rxjava, as follows:
RxTextView.textChanges(editQuery) // I'm using RxBinding for listening to text changes
.flatMap(new Func1<CharSequence, Observable<UserPublic[]>>() {
@Override
public Observable<UserPublic[]> call(CharSequence query) {
return api.searchUsers(query); // I'm using Retrofit 1.9 for network calls. searchUsers returns an Observable<UserPublic[]>
}
})
.subscribe(Observers.create(
new Action1<UserPublic[]>() {
@Override
public void call(UserPublic[] userPublics) {
processResult(userPublics);
}
})
, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
processError(throwable);
}
});
The problem is that if the network call encounters an error, the entire observable site will stop. Therefore, nothing will happen when the user continues to enter
How can I modify this code to:
>Whenever a network problem occurs, processerror > is called. However, when the user continues to enter, a new network call will continue to be issued (leading to processresult / processerror again)
resolvent:
Invalid Sign
This is a naive application that waits 5 seconds and then tries again:
observable
.retryWhen( errorObservable -> errorObservable.delay( 5, TimeUnit.SECONDS ) )
.subscribe();
This is a naive operation. It will retry after timeout. If IOException occurs, it will fail:
observable
.retryWhen( errorObservable -> errorObservable.flatMap( throwable -> { // (1)
if ( throwable instanceof IOException ) {
return Observable.error( throwable ); // (2)
}
return Observable.just(1); // (3)
} )
.subscribe();
>Use flatmap() to postpone the decision until you know the type of error to handle. > the observable returned throws the provided error or other content you want to better describe the problem. > provide an observable object that simply executes onnext() and tells the retrywhen() operator to re subscribe to the original observable object