scala - 如何动态生成具有 for-yield 的并行 future

标签 scala future yield

我有以下代码:

  val f1 = Future(genA1)
  val f2 = Future(genA2)
  val f3 = Future(genA3)
  val f4 = Future(genA4)

val results: Future[Seq[A]] = for {
  a1 <- f1
  a2 <- f2
  a3 <- f3
  a4 <- f4
} yield Seq(a, b, c, d)

现在我需要选择性地排除a2,如何修改代码? (使用 map 或 flatMap 也可以)

此外,假设我有 M 个可能的 future 需要像上面那样聚合,并且 M 中的 N 个可以选择性地排除某个标志(商业逻辑),我应该如何处理?

提前致谢!

莱昂

最佳答案

在问题 1 中,我知道您希望从给定逻辑的序列中排除一个条目(例如 B),而在问题 2 中,您希望从总共 M 个条目中抑制 N 个条目,并根据这些结果计算 future 。我们可以将这两种情况概括为如下所示:

// Using a map as simple example, but 'generators' could be a function that creates the required computation
val generators = Map('a' -> genA1, 'b' -> genA1, 'c' -> genA3, 'd' -> genA4)
...
// shouldAccept(k) => Business logic to decide which computations should be executed.
val selectedGenerators = generators.filter{case (k,v) => shouldAccept(k)}
// Create Seq[Future] from the selected computations
val futures = selectedGenerators.map{case (k,v) => Future(v)}
// Create Future[Seq[_]] to have the result of computing all entries.
val result = Future.sequence(futures)

一般来说,我认为您正在寻找的是 Future.sequence,它采用 Seq[Future[_]] 并生成 Future[ Seq[_]],这基本上就是您通过 for 理解“手动”执行的操作。

关于scala - 如何动态生成具有 for-yield 的并行 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23605673/

相关文章:

javascript - JavaScript 中的 Deferred、Promise 和 Future 有什么区别?

java - 如何继承 CompletableFuture?

javascript - 如何在异步生成器函数中引发错误

arrays - 使用 Ruby 生成多重集的分区

c# - Objective-C 中是否有与 C# 的 yield 关键字相似的地方

scala - 来自 Spark Streaming 的 Rest API 服务调用

json - 如何将JSON空值解码为空集合

Scala 线程池 - 同时调用 API

scala - Play Framework 2.X 和阻塞数据库调用

Scala:更有效的过滤列表和创建 future 序列的方法