多个异步调用之间的两个链式调用

Mat*_*ios 1 asynchronous kotlin

我的 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())
}      
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我找不到一种方法使一个请求依赖于另一个请求。就我而言,我需要 cFetcher 等到 bFetcher 结束工作后再开始。

在 Kotlin 中执行此操作的正确方法是什么?

Ten*_*r04 6

只要让应该同步的部分同步就可以了。

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())
}      
Run Code Online (Sandbox Code Playgroud)

如果您有多个依赖项并希望并行运行它们,我想您可以执行以下操作:

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())
}      
Run Code Online (Sandbox Code Playgroud)