kotlin - 如何启动并行协程并返回结果

标签 kotlin coroutine kotlin-coroutines

我正在尝试编写一个异步运行2个操作并使用Kotlin协程返回结果的函数。例如,我希望自己的getData方法大致同时运行我的两个longRunningOperationX方法,以便我更快地得到合并的结果:

fun getData(): String {
  val stringOne = longRunningStringOperationOne()
  val stringTwo = longRunningStringOperationTwo()
  return stringOne + stringTwo
}
在Kotlin中,我可以使用launchasync方法运行这些操作。
fun getData(): String {
  GlobalScope.launch { 
    val stringOne = async { longRunningStringOperationOne() }
    val stringTwo = async { longRunningStringOperationTwo() }
    println("result: $stringOne + $stringTwo")
    // return "result: $stringOne + $stringTwo" <- not allowed
  }
  return "?"
}
但是,您可能知道,Coroutine范围内的操作结果无法在GlobalScope之外访问,因此,在长时间运行的操作完成之前,我的方法只需要返回当时的值即可。
那么,给定这个问题的空间-一个返回结果的非挂起(不是kotlin suspend fun)函数-我该如何异步(并行)运行两个长时间运行的操作,但是在返回结果之前使用Kotlin协程返回它们呢?

最佳答案

您将要使用Structured Concurrency代替Global Scope,并用await() async返回的Jobs。一种方法是这样的:

fun getData(): String {
  return runBlocking { 
    val stringOne = async { longRunningStringOperationOne() }
    val stringTwo = async { longRunningStringOperationTwo() }
    "result: ${stringOne.await()} + ${stringTwo.await()}")  // will be the return value of the runBlocking lambda
  }
}

关于kotlin - 如何启动并行协程并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62923291/

相关文章:

java - Java 8 重载可以区分函数参数参数类型吗?

c# - 在协程中使用 Quaternion.RotateTowards() 旋转对象?

kotlin - 另一个作业完成后重新创建作业

java - Kotlin 协程在进行网络调用时如何知道何时让步?

kotlin - 我们什么时候使用launch(SupervisorJob())?

Kotlin Actor 到 Actor 的通信

Kotlin 不可空映射允许删除 null

Kotlin when(Pair<>),还有其他方法吗?

kotlin - 定位JavaScript时在Kotlin协程中使用runBlocking?

kotlin - Job 作为 CoroutineScope 和 launch 的参数有什么不同?