score:3

Accepted answer

it does not work sequentially, it just cannot start the futures till they are created (which would happen in your case in your flatmap of your previous future), so you need to create them in advance if you want to process them in parallel (with the usual implicit executioncontexts).

probably this tutorial explains better though (it complicates it with withfilter):

the purchase future is completed only once both usdquote and chfquote are completed– it depends on the values of both these futures so its own computation cannot begin earlier.

the for-comprehension above is translated into:

val purchase = usdquote flatmap { usd => chfquote .withfilter(chf => isprofitable(usd, chf)) .map(chf => connection.buy(amount, chf)) }

which is a bit harder to grasp than the for-comprehension, but we analyze it to better understand the flatmap operation. the flatmap operation maps its own value into some other future. once this different future is completed, the resulting future is completed with its value. in our example, flatmap uses the value of the usdquote future to map the value of the chfquote into a third future which sends a request to buy a certain amount of swiss francs. the resulting future purchase is completed only once this third future returned from map completes.

what you would really only need is something like map2 instead of flatmap, as you do not use the returned value from the previous future to create the new future.


Related Query

More Query from same tag