返回Kotlin协同程序中产生的值

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

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

阻止,直到结果可用。