Retry API on fail using rxjava retryWhen android
If you have requirement where you want to retry api you can take advantage rxjava retryWhen operator with below function. here with use of custom function you can add logic to check http status when you want api to retry and max number of time you want api to be retried.
public class RetryWithDelay implements Function<Observable<? extends Throwable>, Observable<?>> { private long delay; private final int max = 2; private int count; public RetryWithDelayPresenter(final long delay) { delay = delay; count = 0; } @Override public Observable<?> apply(Observable<? extends Throwable> observable) { return observable .flatMap(throwable -> { if (throwable instanceof RetrofitException) { final RetrofitException error = (RetrofitException) throwable; if (error.getKind() == RetrofitException.Kind.HTTP) { final Response response = error.getResponse(); if (response.code() == /* check http status code needed*/) { if (++count < max) { return Observable.timer(delay, TimeUnit.MILLISECONDS); } } } count = max; return Observable.error(throwable); } return Observable.error(throwable); }); }to use above function you need to use with rxjava retryWhen function presenter.apiCall().retryWhen(DELAY_TIME)
Comments
Post a Comment