我终于为所有感兴趣的人做了这样的事情:
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) {
// Let the underlying method do the job of retrying.
}
});
有了这个,我必须将标准的Callback 传递给enqueueWithRetry 方法,它让我实现onFailure(虽然在前面的方法中我也可以实现它)
这就是我解决问题的方法。任何关于更好设计的建议将不胜感激。