當它只回傳一個值時,我可以使用 async 呼叫一個函式。
但是,如果回報是一對,我得到 -Destructuring declaration initializer of type Deferred<Unit> must have a 'component1()' function
我錯過了什么嗎?
這是一個示例代碼:
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val num = 11
val a = async { oneValue(num) }
println(a.await()) // returns 22
// This doesn't compile
val (b, c) = async { twoValues(num) } // Destructuring declaration initializer of type Deferred<Unit> must have a 'component1()' function
println(b.await())
println(c.await())
// Same code works without async-await
val (d, e) = twoValues(num)
println(d)
println(e)
}
suspend fun oneValue(num: Int): Int {
return num * 2
}
suspend fun twoValues(num: Int): Pair<Int, Boolean> {
return Pair(num * 2, true)
}
uj5u.com熱心網友回復:
問題是你只能以Pair這種方式解構,而不能解構Deferred它本身。
您可以先將延遲值分配給單個變數,然后再將await其分配給一個Pair可以解構的變數:
val deferredPair = async { twoValues(num) }
// do other stuff concurrently
val (b, c) = deferredPair.await()
println(b)
println(c)
如果您真的不需要同時執行任何操作 this twoValues(),您也可以直接呼叫它(就像您在上一個示例中所做的那樣):
val (b, c) = twoValues(num)
println(b)
println(c)
請注意,在這里您的掛起函式會執行其整個計算,然后回傳Pair2 個計算物件中的一個。它不提供等待部分內容的可能性。這可能是您正在尋找的,所以應該沒問題。
如果您需要 2 個可以獨立等待的獨立計算,則需要啟動 2 個協程,這會使事情變得有點復雜。如果這是您想要的,最有可能的是,計算可能足夠獨立,可以放入 2 個不同的掛起函式中,您可以在 2 個單獨的異步中呼叫這些函式(因此您回到了具有單個回傳值的已知情況)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429815.html
