Last active
February 2, 2020 13:15
-
-
Save talosdev/333918e286b241b45316bcea94f08bae to your computer and use it in GitHub Desktop.
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 Function<Observable<? extends Throwable>, Observable<?>> { | |
private final int maxRetries; | |
private final int retryDelayMillis; | |
private int retryCount; | |
public RetryWithDelay(final int maxRetries, final int retryDelayMillis) { | |
this.maxRetries = maxRetries; | |
this.retryDelayMillis = retryDelayMillis; | |
this.retryCount = 0; | |
} | |
@Override | |
public Observable<?> apply(final Observable<? extends Throwable> attempts) { | |
return attempts | |
.flatMap(new Function<Throwable, Observable<?>>() { | |
@Override | |
public Observable<?> apply(final Throwable throwable) { | |
if (++retryCount < maxRetries) { | |
// When this Observable calls onNext, the original | |
// Observable will be retried (i.e. re-subscribed). | |
return Observable.timer(retryDelayMillis, | |
TimeUnit.MILLISECONDS); | |
} | |
// Max retries hit. Just pass the error along. | |
return Observable.error(throwable); | |
} | |
}); | |
} | |
} | |
// USAGE: | |
// Add retry logic to existing observable. | |
// Retry max of 3 times with a delay of 2 seconds. | |
observable | |
.retryWhen(new RetryWithDelay(3, 2000)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment