Scala-先完成条件的未来列表 [英] Scala - Future List first completed with condition

查看:87
本文介绍了Scala-先完成条件的未来列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of Futures and I want to get the first one completed with a certain condition. Here is an example of a possible code:

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
}

但是它效率不高,因为我只使用列表中的一个元素,但是计算所有这些元素都有很多延迟.

But it's not efficient, because I'll take only one element of the list, but computed all of them with a lot of latency.

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

I know firstCompletedOf but it's not what I'm searching.

(对不起,我的英语不好.)

(Sorry for my bad English.)

推荐答案

请尝试使用Promise,并在满足条件的将来完成后立即对其调用trySuccess.

Try using a Promise and calling trySuccess on it as soon as a future that satisfies the condition completes. The first to call trySuccess will complete the future, the following ones will have no effect (as opposed to calling success, which can only be called once on a Promise).

请记住,如果列表中没有任何一个未来满足条件,您将永远不会有结果,即,承诺未来将永远不会完成.

Keep in mind that if no future in the list satisfies the condition, you will never have a result, i.e. the promise future will never complete.

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

这篇关于Scala-先完成条件的未来列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆