繁体   English   中英

暂停kotlin coroutine异步子功能

[英]Suspend kotlin coroutine async subfunction

我有一个异步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环境中运行)

您可以这样做,将回调转换为暂停功能

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)
    }
} 

不太好但是有渠道的工作解决方案:

    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)
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM