具有回报价值的Kotlin协同程序

我想创建一个具有返回值的协程方法。

例如)

fun funA() = async(CommonPool) { return 1 } fun funB() = async(CommonPool) { return 2 } fun sum() { launch { val total = funA().await() + funB().await() } } 

如果我想要返回总和方法,我该怎么办?

喜欢,

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

为了精确返回Int ,你需要退出协程,这就是runBlocking的作用:

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

请参阅协程指南中的桥接阻塞和非阻塞世界 ,以及如果要协程中使用sum ,请编写暂停函数 。