返回Kotlin协程中生成的值

时间:2017-06-07 13:36:23

标签: kotlin coroutine

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

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()
}

我还考虑过使用事件总线,但这个问题有更优雅的解决方案吗?

提前致谢。

2 个答案:

答案 0 :(得分:11)

你可以做到

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

阻止,直到结果可用。

答案 1 :(得分:0)

您可以使用:

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()
    }

 }