简体   繁体   中英

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

How can I wait for the returned result and return it outside of the async Unit . Therefore await the call to the Unit by the subfunction.

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 must not be a suspend function, however it could be embedded into a helper function.

(the code has to run in an Android enviroment)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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