OkHttpClient cannot cancel Call by tag

一曲冷凌霜 提交于 2019-11-30 08:44:08

问题


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.

Stated in the CHANGELOG here:

Canceling batches of calls is now the application's responsibility. The API to cancel calls by tag has been removed and replaced with a more general mechanism. The dispatcher now exposes all in-flight calls via its runningCalls() and queuedCalls() methods. You can write code that selects calls by tag, host, or whatever, and invokes Call.cancel() on the ones that are no longer necessary.

I'm self-answering this post with my simple utility method to cancel a running or queued Call by tag.


回答1:


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



来源:https://stackoverflow.com/questions/35964663/okhttpclient-cannot-cancel-call-by-tag

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