有顺序的Future.find吗? [英] Is there sequential Future.find?

查看:141
本文介绍了有顺序的Future.find吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些副作用函数,

  def f():Future [Int] = {
val n = Random.nextInt()
println(sGenerated $ n)
Future(n)
}

,我想重复执行它直到谓词返回true。

  def成功(n:Int):布尔= n%2 == 0 

我的计划是建立 Stream 结果

  val s = Stream.fill(10)(f )

然后使用 Future.find 来获得满足谓词的第一个结果。

  Future.find(s)(成功)map println 

问题在于 Future.find 并行运行所有期货,希望它依次执行期货,直到谓词返回true。

  scala> Future.find(s)(成功)map println 
已生成-237492703
已生成-935476293
已生成-1155819556
已生成-375506595
生成-912504491
生成-1307379057
生成-1522265611
生成1163971151
生成-516152076
res8:scala.concurrent.Future [Unit] = scala.concurrent.impl.Promise$DefaultPromise@37d28f02
一些(-1155819556)

问题是如何顺序执行期货流,直到谓词返回真正?在标准库或第三方库中是否有适合的函数?

解决方案

不使用流,我建议使用另一种方法。使用未来的筛选器并以递归方式恢复:

  def findFirst [A](futureGen:=> Future [A],谓词: A => Boolean):Future [A] = {
futureGen.filter(predicate).recoverWith {case _ => findFirst(futureGen,predicate)}
}

findFirst(f,success)

这将一个接一个地调用期货,直到'成功'将返回true。

I have some side-effectful function,

def f(): Future[Int] = {
  val n = Random.nextInt()
  println(s"Generated $n")
  Future(n)
}

and I want to execute it repeatedly until predicate returns true.

def success(n: Int): Boolean = n % 2 == 0

My plan is to build Stream of results

val s = Stream.fill(10)(f)

and then use Future.find to get the first result that satisfies predicate.

Future.find(s)(success) map println

The problem is that Future.find runs all the futures in parallel and I want it to execute futures sequentially one after the other until predicate returns true.

scala> Future.find(s)(success) map println
Generated -237492703
Generated -935476293
Generated -1155819556
Generated -375506595
Generated -912504491
Generated -1307379057
Generated -1522265611
Generated 1163971151
Generated -516152076
res8: scala.concurrent.Future[Unit] = scala.concurrent.impl.Promise$DefaultPromise@37d28f02
Some(-1155819556)

The question is how to execute stream of futures sequentially until predicate returns true? Are there any suitable functions in standard or third-party library?

解决方案

Instead of using Stream I suggest using another approach. Using The Future's filter and recoverWith recursively:

def findFirst[A](futureGen: => Future[A], predicate: A => Boolean): Future[A] = {
  futureGen.filter(predicate).recoverWith { case _ => findFirst(futureGen, predicate) }
}

findFirst(f, success)

This will call the Futures one after the other until 'success' will return true.

这篇关于有顺序的Future.find吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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