java Retrofit 2/OkHttp:取消所有正在运行的请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34367910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:49:19  来源:igfitidea点击:

Retrofit 2/OkHttp: Cancel all running requests

javaandroidretrofitokhttp

提问by Shubhadeep Chaudhuri

I'm using Retrofit 2-beta2 with OkHttp 2.7.0.

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

To get the OkHttpClientobject from Retrofit I'm using the Retrofit .client()method and to cancel all it's running requests, I'm calling it's cancel(Object tag)method but the requests still keep running and I get a response.

为了OkHttpClient从 Retrofit 中获取对象,我使用了Retrofit .client()方法并取消了它正在运行的所有请求,我调用了它的cancel(Object tag)方法,但请求仍然继续运行并且我得到了响应。

Even the client's Dispatcher's getQueuedCallCount()and getRunningCallCount()return 0 after calling cancel().

即使客户DispatchergetQueuedCallCount()getRunningCallCount()返回0调用cancel()之后。

Is there anything else that I need to do for this to work? Or could it be a bug in OkHttp?

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

As a workaround, I'm calling shutdownNow()on the client's ExecutorServicebut I'd prefer a cleaner solution.

作为一种解决方法,我正在拜访shutdownNow()客户,ExecutorService但我更喜欢更简洁的解决方案。

回答by Shubhadeep Chaudhuri

UPDATE:This is now much easier to achieve in OkHttp 3 by using Dispatcherwhich has a cancelAll()method. The dispatcher is returned from OkHttpClient.dispatcher().

更新:现在通过使用Dispatcherwhich 有一个cancelAll()方法,这在 OkHttp 3 中更容易实现。调度程序从 返回OkHttpClient.dispatcher()

Old Solution:The only way to do this (that I could find) is to create a subclass of OkHttpClientand use that with Retrofit.

旧解决方案:执行此操作的唯一方法(我能找到)是创建一个子类OkHttpClient并将其与 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());
    }
}

The following line cancels all requests with tag TAG_CALL. Since the class above sets TAG_CALLon all requests, so all requests are cancelled.

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

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