There is a special operator that can be used in this case:
public final Observable<T> retryWhen(final Func1<? super Observable<? extends Throwable>, ? extends Observable<?>> notificationHandler)
If you implement it you will see what parameters it accepts:
observable.retryWhen(new Func1<Observable<? extends Throwable>, Observable<T>>() {
@Override
public Observable<T> call(final Observable<? extends Throwable> error) {
}
});
You can see, that you get the error that was thrown by OkHttp. It is always throwing HttpException
, if you call:
httpException.code()
You will get HTTP code number.
So the implementation of the function above might look like:
observable.retryWhen(new Func1<Observable<? extends Throwable>, Observable<T>>() {
@Override
public Observable<T> call(final Observable<? extends Throwable> error) {
return error.flatMap(doRelogging());
}
});
I have made a small library, that does what you expect:
RetrofitRxErrorHandler
You might try it or just look into sources for more advanced retry strategies regarding fetching API errors.