News for hackers. Stuff that matters.
Re:A Little Guide on Using Concurrent Futures for Web Develo... by jacobenget on Wednesday September 16, 2015 @06:03PM (#10230219)
I appreciate the article. I was confused by one part though. You talk about how to combine multiple Futures into a Future of a tuple and give two example on how to do this. One that will not execute the futures in parallel:

  // Returns Future[(User, Seq[Message], Seq[JobOffer])]
  // ** NOT EXECUTED IN PARALLEL **
  val result = for ( 
    user     <- userByEmail("[email protected]");  // User
    messages <- newMessages;  // Seq[Messages]                         
    offers   <- newOffers   // Seq[JobOffer]                             
  ) yield {
    // do something here
    (user, messages, offers)
  }
and another that will:

  // Futures are created here
  val userF = userByEmail("[email protected]"); 
  val messagesF = newMessages
  val offersF = newOffers

  // Returns Future[(User, Seq[Message], Seq[JobOffer])]
  // ** Executed in parallel **
  for (
       user     <- userF;
       messages <- messagesF;
       offers   <- offersF
       ) yield {
         (user, messages, offers)
  }
and I'm having a hard time seeing the essential difference between these two bits of code. How is it that creating the futures before the 'for' expression results in the Future of the tuple being executed in parallel? I'm thinking that the 'for' expression gets expanded to basically the same flatMap/map expression in both cases. And that each 'step' in this flatMap/map expression can only be evaluated after the previous 'step' has finished, so neither of these approaches will run in parallel.

There are no comments on this comment yet.