Kotlin Coroutines 的 `Async/Await` 的非挂起版本是什么?
What's the non-suspending version of `Async/Await` for Kotlin Coroutines?
fun nonSuspendingFunction(): Boolean {
return async(UI) { true }
.await() // compiler error, can be called only within a suspending function
}
是否有可以在 Deferred<T>
的挂起函数之外调用的 .await()
版本?我想阻塞当前线程直到 Deferred<T>
returns.
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
fun nonSuspendingFunction(): Boolean {
return async(UI) { true }
.await() // compiler error, can be called only within a suspending function
}
是否有可以在 Deferred<T>
的挂起函数之外调用的 .await()
版本?我想阻塞当前线程直到 Deferred<T>
returns.
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