如何解决非暂停函数中Kotlin协程的返回值
我有一个要覆盖的功能,因此无法用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()
的调用方?
解决方法
我需要引入一个非阻塞延迟
从呼叫者的角度来看,您希望它如何工作?
由于函数的签名,您必须阻塞调用线程,直到String准备就绪为止。无论使函数的内部结构多么复杂(或异步),约束仍然存在:调用者必须同步等待。
在这里使用runBlocking
可以做到这一点:使调用者线程实际 block ,直到内部完成所有操作为止。这就是为什么如果包装launch
的全部内容就没有必要使用runBlocking
的原因。相反,您可以直接直接致电doAnotherThing()
:
override fun doSmth(): String {
return runBlocking {
delay(1000L)
doAnotherThing() // last expression is the return value
}
}
话虽如此,如果您仍然阻塞了调用线程,为什么不只使用 blocking Thread.sleep()
呢?
override fun doSmth(): String {
Thread.sleep(1000L)
return doAnotherThing()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。