我试图返回从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)
阻止,直到结果可用.
| 归档时间: |
|
| 查看次数: |
4755 次 |
| 最近记录: |