How can I add retry functionality to the requests sent by Retrofit 2 library. Something like:
service.listItems().enqueue(new Callback>
I did something quite similar to Ashkan Sarlak, but since Retrofit 2.1 passes the Call
into the onFailure
method, you can simplify to one CallbackWithRetry
abstract class. See:
public abstract class CallbackWithRetry implements Callback {
private static final String TAG = "CallbackWithRetry";
private int retryCount = 0;
private final Logger logger;
private final String requestName;
private final int retryAttempts;
protected CallbackWithRetry(@NonNull Logger logger, @NonNull String requestName, int retryAttempts) {
this.logger = logger;
this.requestName = requestName;
this.retryAttempts = retryAttempts;
}
@Override
public void onFailure(Call call, Throwable t) {
if (retryCount < retryAttempts) {
logger.e(TAG, "Retrying ", requestName, "... (", retryCount, " out of ", retryAttempts, ")");
retry(call);
retryCount += 1;
} else {
logger.e(TAG, "Failed request ", requestName, " after ", retryAttempts, " attempts");
}
}
private void retry(Call call) {
call.clone().enqueue(this);
}
}