OkHttpClient cannot cancel Call by tag

前端 未结 1 743
南方客
南方客 2020-12-18 06:27

I recently upgraded to OkHttp3, and noticed that you could no longer cancel a Call by tag directly from the Client. This has to be handled by the application now.

St

相关标签:
1条回答
  • 2020-12-18 06:31

    Use the following utility class to cancel a running or queued Call by tag:

    public class OkHttpUtils {
        public static void cancelCallWithTag(OkHttpClient client, String tag) {
            // A call may transition from queue -> running. Remove queued Calls first.
            for(Call call : client.dispatcher().queuedCalls()) {
                if(call.request().tag().equals(tag))
                    call.cancel();
            }            
            for(Call call : client.dispatcher().runningCalls()) {
                if(call.request().tag().equals(tag))
                    call.cancel();
            }
        }
    }
    

    I created an example, with a test case here: https://gist.github.com/RyanRamchandar/64c5863838940ec67f03

    0 讨论(0)
提交回复
热议问题