返回Kotlin协程中生成的值

DE_*_*TBH 5 coroutine kotlin

我试图返回从coroutine生成的值

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

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

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

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

提前致谢.

Kir*_*man 16

你可以做

val result = runBlocking(CommonPool) {
    suspendingFunctionThatReturnsMyValue()
}
Run Code Online (Sandbox Code Playgroud)

阻止,直到结果可用.

  • @DmytroDanylyk`withContext`是一个`suspend`函数。有问题的代码在常规函数中。 (2认同)