Kotlin Coroutines with returning value

前端 未结 6 874
盖世英雄少女心
盖世英雄少女心 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:07

    Here's another way to run funA() and funB() in parallel without using runBlocking.

    fun funA() = CoroutineScope(Dispatchers.IO).async {
        delay(3000)
        return@async 1
    }
    
    fun funB() = CoroutineScope(Dispatchers.IO).async {
        delay(3000)
        return@async 2
    }
    
    fun sum() = CoroutineScope(Dispatchers.IO).async {
        val a = funA()
        val b = funB()
        return@async a.await() + b.await()
    }
    

    And if you want to run sum() without blocking the main thread,

    CoroutineScope(Dispatchers.IO).launch {
        measureTimeMillis {
            Log.d("TAG", "sum=${sum().await()}")
        }.also {
            Log.d("TAG", "Completed in $it ms")
        }
    }
    

提交回复
热议问题