Sebastian Schneider
Sebastian Schneider

Reputation: 5552

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)

Upvotes: 3

Views: 345

Answers (2)

Francesc
Francesc

Reputation: 29330

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

Upvotes: 1

Andrei Tanana
Andrei Tanana

Reputation: 8442

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

Upvotes: 0

Related Questions