Using for-comprehensions for futures
In this small recipe, we will see how to use for comprehensions to iterate over futures as we do with Scala collections. As a future is a monad, like a list in Scala, we can operate on it in the same way as we operate on a list. It is also a way of composing futures.
Getting ready
All the prerequisites are the same as before; just import the Hello-Akka
project in the IDE.
How to do it...
- Create a Scala file,
ForComprehensions.scala
, in thecom.packt.chapter4
package. - Add the following imports to the top of the file:
import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global
- Create a test application, as follows:
object ForComprehensions extends App { val futureA = Future(20 + 20) val futureB = Future(30 + 30) val finalFuture: Future[Int] = for { a <- futureA b <- futureB } yield...