Skip to content

Instantly share code, notes, and snippets.

@NaserKhoshfetrat
Forked from milechainsaw/BackoffCallback.java
Created November 9, 2020 16:43
Show Gist options
  • Save NaserKhoshfetrat/3241dd0c1cbf61c8c6c19495524158ed to your computer and use it in GitHub Desktop.
Save NaserKhoshfetrat/3241dd0c1cbf61c8c6c19495524158ed to your computer and use it in GitHub Desktop.
Exponential backoff support for Retrofit2.
/**
* Created by milechainsaw on 7/19/16.
*
* Exponential backoff callback for Retrofit2
*
*/
public abstract class BackoffCallback<T> implements Callback<T> {
private static final int RETRY_COUNT = 3;
/**
* Base retry delay for exponential backoff, in Milliseconds
*/
private static final double RETRY_DELAY = 300;
private int retryCount = 0;
@Override
public void onFailure(final Call<T> call, Throwable t) {
retryCount++;
if (retryCount <= RETRY_COUNT) {
int expDelay = (int) (RETRY_DELAY * Math.pow(2, Math.max(0, retryCount - 1)));
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
retry(call);
}
}, expDelay);
} else {
onFailedAfterRetry(t);
}
}
private void retry(Call<T> call) {
call.clone().enqueue(this);
}
public abstract void onFailedAfterRetry(Throwable t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment