Kotlin Coroutines with returning value

Expert wanna be picture Expert wanna be · Nov 1, 2017 · Viewed 38.5k times · Source

I want to create a coroutine method which has returning value.

For example)

fun funA() = async(CommonPool) {
    return 1
}

fun funB() = async(CommonPool) {
    return 2
}

fun sum() {
    launch {
        val total = funA().await() + funB().await()
    }
}

If I want to return total in sum method, how should I do?

like,

fun sum(): Int {
    launch {
        val total = funA().await() + funB().await()
    }   

    return total
}

Answer

Alexey Romanov picture Alexey Romanov · Nov 1, 2017

To return exactly Int, you need to get out of the coroutine world and that's what runBlocking is for:

fun sum(): Int = runBlocking {
    funA().await() + funB().await()
}

See Bridging blocking and non-blocking worlds in the coroutine guide, and Composing suspending functions for how to do it if you want to use sum inside coroutines.