【问题标题】:What's the non-suspending version of `Async/Await` for Kotlin Coroutines?Kotlin 协程的 `Async/Await` 的非暂停版本是什么?
【发布时间】:2018-08-17 12:44:31
【问题描述】:
fun nonSuspendingFunction(): Boolean {
return async(UI) { true }
.await() // compiler error, can be called only within a suspending function
}
是否有可以在Deferred<T> 的挂起函数之外调用的.await() 版本?我想阻塞当前线程,直到Deferred<T> 返回。
【问题讨论】:
标签:
kotlin
kotlinx.coroutines
【解决方案1】:
runBlocking 就是你要找的东西。
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
fun blocks() = runBlocking {
async { true }.await()
}
我刚刚用一个非常简单的main 函数测试了上面的代码:
fun main(args: Array<String>) {
blocks().let(::println)
}
输出:
true