Last active
January 13, 2021 09:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
}); | |
} | |
} |
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
Test