Skip to content

Instantly share code, notes, and snippets.

@jsaund
Created July 13, 2017 00:15
Show Gist options
  • Save jsaund/c903a4cd23391f372ebbe7bb75f434e9 to your computer and use it in GitHub Desktop.
Save jsaund/c903a4cd23391f372ebbe7bb75f434e9 to your computer and use it in GitHub Desktop.
A collection of RxUtils for Android
public class RxUtils {
private RxUtils() {
}
@NonNull
public static Func1<Observable<? extends Throwable>, Observable<?>> retryWithBackoff(
final int maxAttempts, final long initialDelay, final TimeUnit unit) {
return errors -> errors
.zipWith(Observable.range(1, maxAttempts), (error, attempt) -> {
if (!isRetryable(error)) {
return new Pair<>(error, maxAttempts);
}
return new Pair<>(error, attempt);
})
.flatMap(pair -> {
final int attempt = pair.second;
if (attempt == maxAttempts) {
return Observable.error(pair.first);
}
final long delay = (long) Math.pow(initialDelay, attempt);
return Observable.timer(delay, unit);
});
}
private static boolean isRetryable(@NonNull Throwable error) {
if (error instanceof HttpException) {
final HttpException httpException = (HttpException) error;
final int code = httpException.code();
return code == 500 || code == 503;
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment