我正在尝试返回从协程生成的值
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()
}
阻塞直到结果可用。
关于kotlin - 返回 Kotlin 协程中生成的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44414272/