Is there sequential Future.find?

后端 未结 3 1504
春和景丽
春和景丽 2021-01-14 08:07

I have some side-effectful function,

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

and I

3条回答
  •  猫巷女王i
    2021-01-14 09:00

    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.

提交回复
热议问题