Is there sequential Future.find?

后端 未结 3 1494
春和景丽
春和景丽 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条回答
  •  [愿得一人]
    2021-01-14 09:08

    First, let's make the futures we aren't interested in fail:

    val s1 = s.map(_.filter(success))
    

    Now you can combine two such futures and get the first successful value using fallbackTo. And just fold the stream, starting with a known-bad future:

    def firstSuccess[T](stream: Stream[Future[T]]): Future[T] = 
      if (stream.isEmpty)
        Future.failed(new NoSuchElementException)
      else
        stream.head.fallbackTo(firstSuccess(stream.tail))
    

提交回复
热议问题