我的 Kotlin 應用程式中有一個如下所示的方法:
coroutineScope{
val aFetcher = async { a.fetch()}
val bFetcher = async { b.fetch()}
val cFetcher = async { c.fetch()}
val dFetcher = async { d.fetch()}
Merged(a.await(),b.await(),c.await(),d.await())
}
我遇到的問題是我找不到讓一個請求依賴于另一個請求的方法。就我而言,我需要讓 cFetcher 等到 bFetcher 結束作業后再開始。
在 Kotlin 中這樣做的正確方法是什么?
uj5u.com熱心網友回復:
只制作應該同步的部分,同步。
coroutineScope{
val aFetcher = async { a.fetch() }
val dFetcher = async { d.fetch() }
val bResult = b.fetch()
val cFetcher = async { c.fetch(bResult) }
Merged(aFetcher.await(), bResult, cFetcher.await(), dFetcher.await())
}
如果您有多個這些依賴項并希望并行運行它們,您可以執行以下操作,我想:
coroutineScope{
val aFetcher = async { a.fetch() }
val dFetcher = async { d.fetch() }
val bAndCFetcher = async {
val bResult = b.fetch()
bResult to c.fetch(bResult)
}
Merged(aFetcher.await(), bAndCFetcher.await().first, bAndCFetcher.await().second, dFetcher.await())
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374104.html
上一篇:Nuxt2CompositionAPI-如何創建ASYNC布局中間件
下一篇:重新激活時強制重置承諾
