【问题标题】:Two chained invocations among several async invocations几个异步调用中的两个链式调用
【发布时间】:2022-01-09 09:57:09
【问题描述】:

我的 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 中正确的做法是什么?

【问题讨论】:

  • 只是我,还是这看起来像是带有额外步骤的同步代码?如果它们无论如何都需要彼此等待,为什么还要让它们异步?
  • 并非所有步骤都需要相互等待。我有很多没有。
  • 然后从需要等待的步骤之前的步骤中删除异步only。如果c 需要等待b,那么b 异步是没有意义的。

标签: kotlin asynchronous


【解决方案1】:

只做应该同步的部分,同步。

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())
}      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2011-02-20
    • 2023-03-05
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多