我滚动浏览Retrofit的官方documentation并决定在我的项目中实现类似的功能,以便用户始终可以选择取消下载文件,一切都能正常工作。实施适当的方法,如果未能规定以下内容:
service.upload1(file1, str, stringMap, new Callback<ImageUpload>() {
@Override
public void success(final ImageUpload imageUpload, Response response) {
mRecyclerView.post(new Runnable() {
@Override
public void run() {
...
});
}
@Override
public void failure(RetrofitError error) {
if (error.isCanceled()) {
Log.e(TAG, "request is cancelled");
} else {
Log.e(TAG, "other larger issue, i.e. no network connection?");
}
}
但是在失败方法中强调红色 isCanceled 。我不明白是什么问题,因为这个方法我们最初提出了类调用(也许是因为发誓我而不是类Call是RetrofitError?)请告诉我如何修复。 我使用改装1.9,我不需要继续改造2.
答案 0 :(得分:17)
error.isCanceled()
似乎并没有出现在Retrofit中。如果您希望能够取消请求,您可以切换到具有call.cancel()
方法的Retrofit 2,或者在当前版本的Retrofit中,您可以扩展Callback
类以创建您自己的类CancellableCallback
这样:
public class CancellableCallback<T> implements Callback<T> {
private Callback<T> callback;
private boolean canceled;
private CancellableCallback() {}
public CancellableCallback(Callback<T> callback) {
this.callback = callback;
canceled = false;
}
public void cancel() {
canceled = true;
callback = null;
}
@Override
public void success(T o, Response response) {
if (!canceled) {
callback.success(o, response);
}
}
@Override
public void failure(RetrofitError error) {
if (!canceled) {
callback.failure(error);
}
}
}
修改强>
然后您可以像这样使用它:
CancellableCallback callback = new Callback<ImageUpload>() {
@Override
public void success(final ImageUpload imageUpload, Response response) {
mRecyclerView.post(new Runnable() {
@Override
public void run() {
...
});
}
@Override
public void failure(RetrofitError error) {
}
};
service.upload1(file1, str, stringMap, callback);
然后取消它:
if (some condition && callback != null) {
callback.cancel();
}
答案 1 :(得分:7)
您可以取消请求,如:
// something happened, for example: user clicked cancel button
service.cancel();
并获得取消回调,如:
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (call.isCanceled()) {
Log.e(TAG, "request was cancelled");
}
else {
Log.e(TAG, "other larger issue, i.e. no network connection?");
}
}
您可以查看here了解更多信息。
答案 2 :(得分:1)
您应该使用Retrofit 2并更改接口方法签名以返回Call
对象。要执行请求,请调用enqueue
方法。之后,您可以调用cancel
方法取消请求。
答案 3 :(得分:0)
你应该切换到retrofit2,然后写这样的东西 -
service.upload1(file1, str, stringMap, new Callback<ImageUpload>() {
@Override
public void onResponse(Call<ImageUpload> call, Response<Topics> response) {
//retrieve your resbonse body here like this -
// ImageUpload imageUpload = response.body();
mRecyclerView.post(new Runnable() {
@Override
public void run() {
...
});
}
@Override
public void onFailure(Call<ImageUpload> call, Throwable t) {
if (call.isCanceled()) {
Log.e(TAG, "request is cancelled");
} else {
Log.e(TAG, "other larger issue, i.e. no network connection?");
}
}