【发布时间】:2017-11-08 21:39:55
【问题描述】:
我正在尝试返回从协程生成的值
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()
}
我也想过使用事件总线,但有没有更优雅的解决方案来解决这个问题?
提前致谢。
【问题讨论】: