Retrofit 2 / OkHttp: Cancel all running requests

I am using Retrofit 2-beta2 with OkHttp 2.7.0.

To get the OkHttpClient object from Retrofit, I use the Retrofit.client () method and canceled all running requests. I call it cancel (Object tag) , but the requests still continue to work, and I get a response.

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

Is there anything else I need to do for this? Or could it be an error in OkHttp?

As a workaround, I call shutdownNow() on the ExecutorService client, but I would prefer a cleaner solution.

+7
java android retrofit
source share
1 answer

UPDATE: In OkHttp 3, it is much simpler using Dispatcher , which has a cancelAll() method. The dispatcher returns from OkHttpClient.dispatcher() .

Old solution: The only way to do this (I could find) is to subclass OkHttpClient and use it 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 next line cancels all requests with the tag TAG_CALL . Since the class above sets TAG_CALL for all requests, therefore all requests are canceled.

 retrofit.client().cancel(OkHttpClientExt.TAG_CALL); 
+15
source

All Articles