bsky
bsky

Reputation: 20242

How does Future.sequence work?

In Scala, I want to transform a variable of type List[Future[T]] into Future[List[T]].

I know I can use Future.sequence.

How is Future.sequence implemented though?

Upvotes: 2

Views: 1148

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149656

Like this:

/** Simple version of `Futures.traverse`. 
 *  Transforms a `TraversableOnce[Future[A]]` into a `Future[TraversableOnce[A]]`.
 *  Useful for reducing many `Future`s into a single `Future`.
 */
def sequence[A, M[X] <: TraversableOnce[X]]
            (in: M[Future[A]])
            (implicit cbf: CanBuildFrom[M[Future[A]], A, M[A]], 
             executor: ExecutionContext): Future[M[A]] = {
  in.foldLeft(successful(cbf(in))) {
    (fr, fa) => for (r <- fr; a <- fa) yield (r += a)
  }.map(_.result())(InternalCallbackExecutor)
}

It creates a seed Future for foldLeft using Promise.successful and then uses a CanBuildFrom to accumulate all the futures into a sequence, yielding the result of the accumulation at the end.

Upvotes: 1

Related Questions