本文介绍了在协程内部并行运行两个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协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 03:44