【发布时间】:2020-09-27 18:55:25
【问题描述】:
我有一个要覆盖的函数,我不能用suspend 标记它。
override fun doSmth(): String
在里面,我需要引入一个非阻塞延迟,所以我在协程里面使用了kotlinx.coroutines.time.delay。
override fun doSmth(): String {
runBlocking {
GlobalScope.launch {
delay(1000L)
val result: String = doAnotherThing()
// How to return this result from doSmth?
}
}
}
如何将此结果值返回给doSmth()的调用者?
【问题讨论】:
-
你不能这样做。
runBlocking块。但要获得结果,您将使用async而不是launch并在返回的 Deferred 上调用await。
标签: kotlin asynchronous kotlin-coroutines