【问题标题】:Return value from Kotlin coroutines inside a non-suspended function非挂起函数内 Kotlin 协程的返回值
【发布时间】: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


【解决方案1】:

我需要引入一个非阻塞延迟

从调用者的角度来看,您希望它如何工作?

由于您的函数的签名,您必须阻塞调用线程,直到字符串准备好。无论您使函数的内部结构多么复杂(或异步),约束仍然存在:调用者必须同步等待。

在这里使用runBlocking 就是这样做的:让调用者线程真正阻塞,直到里面的一切都完成。这就是为什么如果你包装了runBlocking 的全部内容,使用launch 是没有意义的。相反,您可以直接调用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()
}

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2018-05-31
    • 2018-04-13
    • 2021-10-02
    • 2020-01-27
    • 2019-05-30
    相关资源
    最近更新 更多