September 2018
Intermediate to advanced
398 pages
9h 43m
English
Future has a map and a flatMap method. Therefore, as we saw in Chapter 3, Handling Errors, for Either, we can use Future in a for-comprehension. For instance, we can define three Futures, as follows:
val f1 = Future {1}
val f2 = Future {2}
val f3 = Future {3}
The Futures are simply successfully returning an integer. If we would like to sum up all of the integers we could write the following:
val res = for {
v1 <- f1
v2 <- f2
v3 <- f3
} yield (v1 + v2 + v3)
The res variable will be Future[Int]; hence, we can call Await to get the final value:
val response = Await.result(res, 1 second)
The response would be 6, in our case.
You just learned that inside the for-comprehension, the value from Future can be used and can be ...
Read now
Unlock full access