Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 959
Sebastian Schneider Avatar asked Jul 28 '26 10:07

Sebastian Schneider


1 Answers

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)
    }
} 
like image 163
Francesc Avatar answered Jul 31 '26 00:07

Francesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!