Scala - 未来列表首先完成有条件

Scala - Future List first completed with condition

我有一份期货清单,我想在特定条件下完成第一个。 这是一个可能的代码示例:

val futureList: Future[List[T]] = l map (c => c.functionWithFuture())
val data = for {
           c <- futureList
           }yield c
data onSuccess {
  case x => (x filter (d=> d.condition)).head
}

但效率不高,因为我只取列表中的一个元素,但计算所有元素时会有很多延迟。

我知道 firstCompletedOf 但这不是我要搜索的内容。

(抱歉我的英语不好。)

尝试使用 Promise 并在满足条件的 future 完成后立即对其调用 trySuccess。第一个调用 trySuccess 将完成 future,后面的将没有任何效果(与调用 success 相反,它只能在 Promise 上调用一次)。

请记住,如果列表中没有满足条件的未来,您将永远不会得到结果,即承诺的未来永远不会完成。

import scala.concurrent.{ Await, Future, Promise }
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Random

def condition(x: Int) = x > 50

val futures = (1 to 10) map (x => Future {
  // wait a random number of ms between 0 and 1000
  Thread.sleep(Random.nextInt(1000))
  // return a random number < 100
  Random.nextInt(100)
})

val p = Promise[Int]()
// the first one that satisfies the condition completes the promise
futures foreach { _ filter condition foreach p.trySuccess }
val result = p.future

// Watch out: the promise could never be fulfilled if all the futures are <=50
println("The first completed future that satisfies x>50 is: " + Await.result(result, 10.seconds))