4 ms·
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 h
by jacobenget 11y ago
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("stephan@ubercto.de"); // 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("stephan@ubercto.de");
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.