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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With