Kotlin Coroutines with returning value

前端 未结 6 884
盖世英雄少女心
盖世英雄少女心 2020-12-17 08:54

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

For example)

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

fun funB() = async(Commo         


        
6条回答
  •  被撕碎了的回忆
    2020-12-17 09:11

    Adding another way of achieving it.

    fun sum(): Int {
        var sum: Int = 0
        runBlocking {
            val jobA = async { funA() }
            val jobB = async { funB() }
            runBlocking{
               sum = jobA.await() + jobB.await()
            }
        }
        return sum
    }
    
    suspend fun funA(): Int {
        return 1
    }
    
    suspend fun funB(): Int {
        return 2
    }
    

提交回复
热议问题