5 ms·
It depends. Let's imagine forA, and forB are expressions that evaluate to futures of Ints. This runs them in serial: for { a <- forA b <- forB
by noelwelsh 13y ago
It depends. Let's imagine forA, and forB are expressions that evaluate to futures of Ints. This runs them in serial:
for {
a <- forA
b <- forB
} yield a + b
This runs them in parallel:
val fa: Future[Int] = forA
val fb: Future[Int] = forB
for {
a <- fa
b <- fb
} yield a + b
(I dropped forC from your example as it has a dependency on the result for forA, and thus can't run in parallel.)
- Uchikoma 13y agoThat forC has a dependency on a was the intention, so it needs to be run in serial. I can't see the difference between your examples and so am confused why 1.) is serial 2.) is parallel.
- noelwelsh 13y agoAt the risk of being trite, it's down to the order of evaluation. You know that a for comprehension expands into calls to flatMap and map? So for { a <- forA b <- forB } yield a + b expands to forA flatMap { a => forB map { b => a + b } } Remember that forB creates and returns a future. Only when this future has been created will it start running. It should be apparent that forB is not evaluated till forA's future delivers a value, and thus the future returned by forB will run in serial with the future returned by forA. In the other example the futures are created outside of the for comprehension, and thus start running in parallel.
- Uchikoma 13y agoAh ok, thanks!