OkHttpClient无法取消Call

OkHttpClient无法取消Call

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

问题描述

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

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.

在此处:

我用我的简单实用工具方法自行回答这篇文章,以取消正在运行或排队的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();
        }
    }
}

我创建了一个示例,这里的测试用例:

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

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

07-30 07:34