UtsavShah UtsavShah - 13 days ago 8
Scala Question

How to consume a list of futures as soon as one completes in Scala

I have a bunch of Futures that can complete at extremely different times, something like this:

val results = task.getAssignedFiles map {
file: File => Future[Result] {
<heavy computation>
}
}


Now I want to iterate over
results
as soon as one of the input futures completes, basically poll all the futures in results until one completes, do some processing, and continue until all of them are done. Something like:

while (!results.allCompleted) {
one = results.firstCompletedFuture
process(one)
}

Answer

You're looking for firstCompletedOf.