改装2/OkHttp:取消所有正在运行的请求 [英] Retrofit 2/OkHttp: Cancel all running requests

查看:664
本文介绍了改装2/OkHttp:取消所有正在运行的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

要从Retrofit中获取OkHttpClient对象,我正在使用 Retrofit .client()方法并取消所有正在运行的请求,我称其为

To get the OkHttpClient object 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.

即使客户的Dispatcher getQueuedCallCount() getRunningCallCount()在调用cancel()后返回0.

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

要执行此操作,我还有其他需要做的事情吗?还是可能是OkHttp中的错误?

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

作为一种解决方法,我在客户端的ExecutorService上调用shutdownNow(),但我希望使用更干净的解决方案.

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

推荐答案

更新:现在,使用具有cancelAll()方法的Dispatcher在OkHttp 3中更容易实现这一点.调度程序是从OkHttpClient.dispatcher()返回的.

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

旧解决方案: 唯一可以做到这一点的方法是创建OkHttpClient的子类,并将其与Retrofit一起使用.

Old Solution: The only way to do this (that I could find) is to create a subclass of OkHttpClient and use that with 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的请求.由于上面的类对所有请求都设置了TAG_CALL,因此所有请求都被取消.

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

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

这篇关于改装2/OkHttp:取消所有正在运行的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆