Retrofit 2/OkHttp: Cancel all running requests

后端 未结 1 1789
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 18:24

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

相关标签:
1条回答
  • 2020-12-28 19:12

    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);
    
    0 讨论(0)
提交回复
热议问题