OkHttpClient 无法取消通过标签调用

OkHttpClient cannot cancel Call by tag

我最近升级到 OkHttp3,发现您无法再直接从客户端取消通过标签调用。现在必须由应用程序处理。

CHANGELOG这里声明:

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.

我正在使用我的简单实用方法自行回答此 post 以取消 运行 或按标记排队的呼叫。

使用以下实用程序 class 取消 运行 或按标签排队 Call

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

我创建了一个示例,这里有一个测试用例:https://gist.github.com/RyanRamchandar/64c5863838940ec67f03