如果有人感兴趣,我最近做了类似于这样的事情:
1
首先我创建了一个抽象类CallbackWithRetry
public abstract class CallbackWithRetry<T> implements Callback<T> {
private static final int TOTAL_RETRIES = 3;
private static final String TAG = CallbackWithRetry.class.getSimpleName();
private final Call<T> call;
private int retryCount = 0;
public CallbackWithRetry(Call<T> call) {
this.call = call;
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, t.getLocalizedMessage());
if (retryCount++ < TOTAL_RETRIES) {
Log.v(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
retry();
}
}
private void retry() {
call.clone().enqueue(this);
}
}
使用这个类,我可以做出如下的操作:
serviceCall.enqueue(new CallbackWithRetry<List<Album>>(serviceCall) {
@Override
public void onResponse(Response<List<Album>> response) {
...
}
});
2
这并不完全令人满意,因为我必须两次传递相同的serviceCall
。这可能会让人感到困惑,因为有人可能认为第二个serviceCall
(进入CallbackWithRetry
构造函数的)应该或可以与我们调用enqueue
方法的第一个不同。
所以我实现了一个辅助类CallUtils
:
public class CallUtils {
public static <T> void enqueueWithRetry(Call<T> call, final Callback<T> callback) {
call.enqueue(new CallbackWithRetry<T>(call) {
@Override
public void onResponse(Response<T> response) {
callback.onResponse(response);
}
@Override
public void onFailure(Throwable t) {
super.onFailure(t);
callback.onFailure(t);
}
});
}
}
我可以像这样使用它:
CallUtils.enqueueWithRetry(serviceCall, new Callback<List<Album>>() {
@Override
public void onResponse(Response<List<Album>> response) {
...
}
@Override
public void onFailure(Throwable t) {
}
});
我需要将一个标准的Callback
传递给enqueueWithRetry
方法,这使得我必须实现onFailure
方法(尽管在之前的方法中我也可以实现它)。
因此,这就是我解决问题的方式。如果有更好的设计建议,欢迎提出。
Callback.onFailure(Call<T> call, Throwable t)
方法已经包含了 "call" 参数了,不再需要使用CallUtils
。 - situee