For-Comprehension with dynamic list of Futures

990 views
Skip to first unread message

C.D.

unread,
Oct 15, 2013, 6:48:46 AM10/15/13
to scala...@googlegroups.com
Hi,

I love how powerful for comprehensions are, but I came across a case where I have a dynamic list of futures that need to be executed in parallel and when everything is completed, I would like to process that and return some value, and was not sure how to handle this. Just to exemplify:

def handleFutures(futures: List[Future[Any]]) : Future[String] = {
  for ( d1 <- futures(0)
         d2 <- futures(1) 
         ......
        ) yield { d1.toString + " : " + d2.toString + " : " + .... }
 }

As I mentioned, all the futures should be executed in parallel here and need to handle error cases as well.

What would you guys recommend using here?

Thanks in advance.

√iktor Ҡlang

unread,
Oct 15, 2013, 7:43:31 AM10/15/13
to C.D., scala-user
On Tue, Oct 15, 2013 at 12:48 PM, C.D. <cab...@gmail.com> wrote:
Hi,

I love how powerful for comprehensions are, but I came across a case where I have a dynamic list of futures that need to be executed in parallel and when everything is completed, I would like to process that and return some value, and was not sure how to handle this. Just to exemplify:

def handleFutures(futures: List[Future[Any]]) : Future[String] = {
  for ( d1 <- futures(0)
         d2 <- futures(1) 
         ......
        ) yield { d1.toString + " : " + d2.toString + " : " + .... }
 }


for { list <- Future.sequence(futures) } yield list.mkString(" : ")

Cheers,

 
As I mentioned, all the futures should be executed in parallel here and need to handle error cases as well.

What would you guys recommend using here?

Thanks in advance.

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Viktor Klang
Director of Engineering

Twitter: @viktorklang

√iktor Ҡlang

unread,
Oct 15, 2013, 7:46:01 AM10/15/13
to C.D., scala-user
as in:

scala> for { list <- Future.sequence(futures) } yield list.mkString(":")
res0: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@3d36dff4

scala> res0 onComplete println

scala> Success(1:2:3:4:5:6:7:8:9:10)
Reply all
Reply to author
Forward
0 new messages