In some cases execution of a Future depends on the outcome of an execution of a previous Future. We would use flatMap
and map
to sequence the evaluation of our dependent futures.
On the other hand, in cases when futures are independent of each other, it is only reasonable to execute them concurrently and collect their results, one after another, when ready. The simplest of tricks to achieve this is to write a for-comprehension and pull out the creation of Futures outside of it. A Future
is submitted to an execution context as soon as it is created. If we create the futures prior to entering our for-comprehension, they are all running (or are at the very least scheduled to run) and we utilise the for-comprehension only to collect their results (future values) in sequential manner. While this approach works, let’s see some other ways to do this before we adopt it.
There are many ways to defur a feline. Also, there is more than one way to execute a number of Futures in parallel. Let’s have a look at some of our options.