在协程内部并行运行两个Kotlin协程

编程入门 行业动态 更新时间:2024-10-26 03:33:47
本文介绍了在协程内部并行运行两个Kotlin协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个暂停功能:

suspend fun sendData() : Boolean suspend fun awaitAcknowledge() : Boolean

我想将它们包装在第三个暂停函数中,在其中应该并行执行它们,并且我想通过具有两个返回值来计算最终结果:

and I want to wrap them in a third suspend function in which they should be executed in parallel and I want to calculate the final result by having both return values:

suspend fun sendDataAndAwaitAcknowledge() : Boolean { // TODO execute both in parallel and compare both results }

但是,如果我这样写,

suspend fun sendDataAndAwaitAcknowledge() : Boolean { val sendResult = sendData() val receiveAck = awaitAcknowledge() }

函数将以串行顺序执行,在我的情况下将不起作用.

the functions will be executed in a serial order, which will not work in my case.

来自RxJava,我想实现类似zip运算符的功能:

Coming from RxJava, I would like to achieve something like the zip operator:

Single.zip(awaitAcknowledge(), sendData(), {receiveAck, sendResult -> ...})

如何使用Coroutines做到这一点?

推荐答案

您可以将awaitAll用于此目的:

import kotlinx.coroutines.* suspend fun sendDataAndAwaitAcknowledge() = coroutineScope { awaitAll(async { awaitAcknowledge() }, async { sendData() }) } fun sendData() = true fun awaitAcknowledge() = false fun main() { runBlocking { println(sendDataAndAwaitAcknowledge()) // [false, true] } }

更多推荐

在协程内部并行运行两个Kotlin协程

本文发布于:2023-11-23 09:56:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621021.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   Kotlin   协程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!