如何为Retrofit 2库发送的请求添加重试功能?类似于:
service.listItems().enqueue(new Callback<List<Item>>() {
@Override
public void onResponse(Response<List<Item>> response) {
...
}
@Override
public void onFailure(Throwable t) {
...
}
}).retryOnFailure(5 /* times */);发布于 2016-07-19 20:58:26
我已经定制了回调接口的实现,你可以用它来代替原来的回调。如果调用成功,则调用onResponse()方法。如果在重试设置的重复次数后调用失败,则调用onFailedAfterRetry()。
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);
}https://gist.github.com/milechainsaw/811c1b583706da60417ed10d35d2808f
发布于 2018-10-10 17:16:43
ashkan-sarlak answer工作得很好,我只是想让它跟上时代。
onFailure(Throwable t) 更改为
onFailure(Call<T> call, Throwable t)因此,这使得创建CallbackWithRetry.java变得非常容易,如下所示
public abstract class CallbackWithRetry<T> implements Callback<T> {
private static final int TOTAL_RETRIES = 3;
private static final String TAG = CallbackWithRetry.class.getSimpleName();
private int retryCount = 0;
@Override
public void onFailure(Call<T> call, Throwable t) {
Log.e(TAG, t.getLocalizedMessage());
if (retryCount++ < TOTAL_RETRIES) {
Log.v(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
retry(call);
}
}
private void retry(Call<T> call) {
call.clone().enqueue(this);
}
}就这样!您可以像这样简单地使用它
call.enqueue(new CallbackWithRetry<someResponseClass>() {
@Override
public void onResponse(@NonNull Call<someResponseClass> call, @NonNull retrofit2.Response<someResponseClass> response) {
//do what you want
}
@Override
public void onFailure(@NonNull Call<someResponseClass> call, @NonNull Throwable t) {
super.onFailure(call,t);
//do some thing to show ui you trying
//or don't show! its optional
}
});发布于 2015-09-15 18:29:50
使用RxJava Observable并调用retry()文档:https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators
https://stackoverflow.com/questions/32579754
复制相似问题