Scala Future.sequence()
When we have a sequence of Futures, or a list of Futures, or a collection of Futures, we should use one of the Future combinator APIs, Future.sequence()
, to deal with this scenario.
This Future.sequence()
function converts a list of Futures into a single Future that means collections of Futures into a single Future.
In simple words, List[Future[T]] ======> Future[List[T]]
.
It is also known as composing Futures. The following diagram demonstrates how Scala Future's sequence()
function converts List[Future[T]]
into Future[List[T]]
:

Consider the following example:
scala> val pricesList:List[Future[Int]] = List(Future(1001),Future(999),Future(-2000),Future(1000)) pricesList: List[scala.concurrent.Future[Int]] = List(scala.concurrent.impl.Promise$DefaultPromise@680a66dd, scala.concurrent.impl.Promise$DefaultPromise@2dd8239, scala.concurrent.impl.Promise$DefaultPromise@472698d, scala.concurrent.impl.Promise$DefaultPromise@7b7683d4) scala> val maxPrice:Future[Int...