仅返回更快协程的值 [英] Return value only of the faster coroutine

查看:81
本文介绍了仅返回更快协程的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何并行运行多个协程并仅返回最先完成的协程的值?

How can I run multiple coroutines in parallel and return only the value of the one that finishes first?

在现实生活中,我有两个数据源-数据库 API服务.我不在乎数据从哪里来,我只需要快速.

Real-life scenario, I have two data sources - Database and API service. I don't care where does the data originate from, I just need it fast. How can I query both Database and API service and cancel the other request when the one finishes?

在RxJava世界中,这等于 Amb运算符.如何使用协程实现类似的行为?

In RxJava world this would be equal to Amb operator. How can I achieve similar behaviour using coroutines?

推荐答案

我想出了以下实现:

suspend fun getFaster(): Int = coroutineScope {
    select<Int> {
        async { getFromServer() }.onAwait { it }
        async { getFromDB() }.onAwait { it }
    }.also {
        coroutineContext.cancelChildren()
    }
}

coroutineScope充当其中执行的所有异步调用的父级. select完成后,我们可以取消其余部分.

The coroutineScope acts as a parent to all async calls performed within. After the select finishes we can just cancel the rest.

这篇关于仅返回更快协程的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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