【问题标题】:Suspend kotlin coroutine async subfunction挂起kotlin协程异步子函数
【发布时间】:2019-07-31 18:43:01
【问题描述】:

我有一个异步CoroutineScope,其中可能是(按条件)对子函数的调用,该子函数以异步Unit返回其结果

如何等待返回的结果并将其返回到异步Unit 之外。因此等待子函数对Unit的调用。

例子:

GlobalScope.launch {
    var value: Int = 0
    if (condition) {
        // the subFunction has a Unit<Int> as return type
        subFunction() { result ->
            value = result
        }
    }
    Log.v("LOGTAG", value.toString())
}

如何等待subFunction完成执行后再继续执行代码,或者直接将结果值赋给变量?

subFunction 不得suspend 函数,但它可以嵌入到辅助函数中。

(代码必须在 Android 环境中运行)

【问题讨论】:

  • 如果没有挂起功能,您将无法做到这一点。
  • @Francesc 是否有可能创建一个本地挂起函数来处理这个问题?我无法修改subFunction

标签: android kotlin kotlin-coroutines


【解决方案1】:

您可以这样做,将您的回调转换为挂起函数

GlobalScope.launch {
    var value: Int = 0
    if (condition) {
        // the subFunction has a Unit<Int> as return type
        value = subFunctionSuspend()
    }
    Log.v("LOGTAG", value.toString())
}

suspend fun subFunctionSuspend() = suspendCoroutine { cont ->
    subFunction() { result ->
        cont.resume(result)
    }
} 

【讨论】:

  • 谢谢,如果我没记错的话,您也可以内联subFunctionSuspend。但它有效!
【解决方案2】:

不是很好,但可以使用渠道解决方案:

    GlobalScope.launch {
        val channel = Channel<Int>()
        if (condition) {
            // the subFunction has a Unit<Int> as return type
            subFunction() { result ->
                GlobalScope.launch {
                    channel.send(result)
                    channel.close()
                }
            }
        }
        for (i in channel) {
            println(i)
        }
    }

【讨论】:

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