We know how to compose futures of different types using for-comprehensions, but in this recipe, we will learn how to compose a sequence of futures of the same type.
Import the Hello-Akka
project in the IDE. The other prerequisites are the same as earlier.
- Create a scala file,
RedcuingFutures
, in thecom.packt.chapter4
package. - Add the following imports to the top of the file:
import akka.util.Timeout import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global
- Create a simple application, as follows:
object ReducingFutures extends App { val timeout = Timeout(10 seconds) val listOfFutures = (1 to 10).map(Future(_)) val finalFuture = Future.reduce(listOfFutures)(_ + _) println(s"sum of numbers from 1 to 10 is $ {Await.result(finalFuture, 10 seconds)}") ...