简体   繁体   English

暂停kotlin coroutine异步子功能

[英]Suspend kotlin coroutine async subfunction

I have an async CoroutineScope in which could be (by condition) a call to a subfunction which returns its result in an async Unit 我有一个异步CoroutineScope ,其中可以(通过条件)调用子函数,该子函数在异步Unit返回其结果

How can I wait for the returned result and return it outside of the async Unit . 如何等待返回的结果并将其返回到异步Unit Therefore await the call to the Unit by the subfunction. 因此等待子功能对Unit的调用。

Example: 例:

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

How can I wait for the subFunction to finish executing before continuing the code, or directly assign the result value to the variable? 如何在继续代码之前等待subFunction功能完成执行,或者直接将结果值分配给变量?

subFunction must not be a suspend function, however it could be embedded into a helper function. subFunction 不能suspend函数,但它可以嵌入到辅助函数中。

(the code has to run in an Android enviroment) (代码必须在Android环境中运行)

You can do this, converting your callback to a suspend function 您可以这样做,将回调转换为暂停功能

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

Not very nice but working solution with channels: 不太好但是有渠道的工作解决方案:

    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