Forked from wotomas/RetryWithExponentialBackOff.java
Created
January 6, 2022 15:21
-
-
Save guilherme-v/29eb1ea188f47ee45d8c5072c4698857 to your computer and use it in GitHub Desktop.
Rxjava Retry With Exponential Backoff
This file contains hidden or 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
import java.io.IOException; | |
import java.util.concurrent.TimeUnit; | |
import rx.Observable; | |
import rx.functions.Func1; | |
import rx.functions.Func2; | |
import rx.schedulers.Schedulers; | |
/** | |
* Created by jimmy on 30/05/2017. | |
*/ | |
public class RetryWithExponentialBackOff implements Func1<Observable<? extends Throwable>, Observable<?>> { | |
private final int maxRetries; | |
private final int retryDelayMillis; | |
private long currentRetryCount; | |
public RetryWithExponentialBackOff(final int maxRetries, final int retryDelayMillis) { | |
this.maxRetries = maxRetries; | |
this.retryDelayMillis = retryDelayMillis; | |
this.currentRetryCount = 0; | |
} | |
@Override | |
public Observable<?> call(Observable<? extends Throwable> errors) { | |
return errors | |
.zipWith(Observable.range(1, maxRetries > 0 ? maxRetries : Integer.MAX_VALUE), (Func2<Throwable, Integer, Throwable>) (throwable, attemptNumber) -> throwable) | |
.flatMap(new Func1<Throwable, Observable<Long>>() { | |
@Override | |
public Observable<Long> call(Throwable throwable) { | |
if (throwable instanceof IOException) { | |
long newInterval = retryDelayMillis * (currentRetryCount * currentRetryCount); | |
if (newInterval < 0) { | |
return Observable.error(new Throwable("Interval out of bounds!")); | |
} | |
return Observable.timer(newInterval, TimeUnit.MILLISECONDS, Schedulers.immediate()); | |
} else { | |
return Observable.error(throwable); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment