Skip to content

Instantly share code, notes, and snippets.

@jemshit
Last active January 13, 2021 09:25
Show Gist options
  • Save jemshit/5b913e98c876863205b2de57b581b6f5 to your computer and use it in GitHub Desktop.
Save jemshit/5b913e98c876863205b2de57b581b6f5 to your computer and use it in GitHub Desktop.
RxJava Retry Web Service Connection incrementally if there is Network Kind of Error.
public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {
private int numberOfTry;
private int delay;
private int retryCount = 1;
private final TimeUnit timeUnit;
public RetryWithDelay(int numberOfTry, int delay, TimeUnit timeUnit) {
this.numberOfTry = numberOfTry;
this.delay = delay;
this.timeUnit = timeUnit;
}
@Override
public Observable<?> call(Observable<? extends Throwable> errors) {
return errors
.flatMap(error -> {
if(error instanceof IOException) { // Network Error
int delayFinal = delay * retryCount;
retryCount++;
if (retryCount <= numberOfTry+1) {
// You might want to notify UI with EventBus etc... with Retry duration
Log.d("RetryWithDelay"+" call()", "retryCount " + delayFinal);
return Observable.timer((long) delayFinal, timeUnit);
} else {
return Observable.error(error); // Let them go to onError() after few retries
}
}else{ // Http Error or other Unexpected Error
return Observable.error(error); // Let them go to onError()
}
});
}
}
@jemshit
Copy link
Author

jemshit commented Jan 13, 2021

Screw this, use Coroutine and good-old while loop :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment