小编DE_*_*TBH的帖子

返回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)

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

提前致谢.

coroutine kotlin

5
推荐指数
1
解决办法
4755
查看次数

标签 统计

coroutine ×1

kotlin ×1