返回在 Kotlin 协程中产生的值

Returning a value produced in Kotlin coroutine

我正在尝试 return 从协程生成的值

fun nonSuspending (): MyType {
    launch(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    //Do something to get the value out of coroutine context
    return somehowGetMyValue
}

我想出了以下解决方案(不是很安全!):

fun nonSuspending (): MyType {
    val deferred = async(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    while (deferred.isActive) Thread.sleep(1)
    return deferred.getCompleted()
}

我也想过使用事件总线,但是这个问题有没有更优雅的解决方案?

提前致谢。

你可以做到

val result = runBlocking(CommonPool) {
    suspendingFunctionThatReturnsMyValue()
}

阻止直到结果可用。

你可以使用这个:

private val uiContext: CoroutineContext = UI
private val bgContext: CoroutineContext = CommonPool

private fun loadData() = launch(uiContext) {
 try {
  val task = async(bgContext){dataProvider.loadData("task")}
  val result = task.await() //This is the data result
  }
}catch (e: UnsupportedOperationException) {
        e.printStackTrace()
    }

 }