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