I have some side-effectful function,
def f(): Future[Int] = {
val n = Random.nextInt()
println(s\"Generated $n\")
Future(n)
}
and I
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))