Retrofit 2/OkHttp: 取消所有 运行 请求

Retrofit 2/OkHttp: Cancel all running requests

我正在使用带有 OkHttp 2.7.0 的 Retrofit 2-beta2。

为了从 Retrofit 获取 OkHttpClient 对象,我使用了 Retrofit .client() method and to cancel all it's running requests, I'm calling it's cancel(Object tag) 方法,但请求仍然保持 运行,我得到了响应。

甚至客户端的DispatchergetQueuedCallCount() and getRunningCallCount() return调用cancel()后0.

我还需要做些什么才能让它工作吗?或者它可能是 OkHttp 中的错误?

作为解决方法,我在客户端的 ExecutorService 上调用 shutdownNow(),但我更喜欢更简洁的解决方案。

更新: 现在在 OkHttp 3 中使用具有 cancelAll() 方法的 Dispatcher 更容易实现。调度程序从 OkHttpClient.dispatcher().

返回

旧解: 唯一的方法(我能找到)是创建 OkHttpClient 的子 class 并将其与 Retrofit 一起使用。

class OkHttpClientExt extends OkHttpClient {
    static final Object TAG_CALL = new Object();

    @Override
    public Call newCall(Request request) {
        Request.Builder requestBuilder = request.newBuilder();
        requestBuilder.tag(TAG_CALL);
        return super.newCall(requestBuilder.build());
    }
}

以下行取消所有带有标签 TAG_CALL 的请求。由于上面的 class 对所有请求设置 TAG_CALL,因此所有请求都被取消。

retrofit.client().cancel(OkHttpClientExt.TAG_CALL);