OkHttpClient无法取消Call by tag [英] OkHttpClient cannot cancel Call by tag

查看:202
本文介绍了OkHttpClient无法取消Call by tag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近升级到 OkHttp3 ,并注意到您无法再直接取消标记来自客户。这必须由应用程序现在处理。

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.

CHANGELOG 此处:


取消批次现在应用程序负责调用。
取消按标记调用的API已被删除,并替换为
更通用的机制。调度程序现在通过其runningCalls()和queuedCalls()方法公开所有正在进行的调用
。您可以编写代码
来选择标记,主机或其他任何调用,并在不再需要的函数上调用
Call.cancel()。

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.

我用我的简单实用工具方法自行回答这篇文章,以取消正在运行或排队的Call by tag。

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

推荐答案

使用以下实用程序类取消正在运行或排队的通过标记调用

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

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

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

这篇关于OkHttpClient无法取消Call by tag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆