How to make a list of "Futures"?

I have a collection of Promises . I was looking for an efficient way to create resulting Futures . Currently, the cleanest way I found to combine them was using scalaz Monoid , for example:

  val promises = List(Promise[Unit], Promise[Unit], Promise[Unit]) promises.map(_.future).reduce(_ |+| _).onSuccess { case a => println(a) } promises.foreach(_.success(())) 

Is there a clean way to do this that does not require a crypt?

The number of Futures in the collection will change, and the number of intermediate collections is undesirable.

+5
source share
2 answers

You can use Future.traverse :

 import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.{ Future, Promise } val promises = List(Promise[Unit], Promise[Unit], Promise[Unit]) Future.traverse(promises)(_.future) 

This will give you a Future[List[Unit]] , which does not exactly qualify as a "set of intermediate collections", but is not necessarily ideal. Future.reduce also works:

 Future.reduce(promises.map(_.future))((_, _) => ()) 

This returns a Future[Unit] , which will be satisfied when all futures are completed.

+7
source

Future.sequence is the method you want.

+3
source

All Articles