Retrofit 2/OkHttp: Cancel all running requests

扶醉桌前 提交于 2019-12-30 02:08:12

问题


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

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.

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

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

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


回答1:


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().

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());
    }
}

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);


来源:https://stackoverflow.com/questions/34367910/retrofit-2-okhttp-cancel-all-running-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!