I\'m working on using Futures for the first time in Scala and am working through an example of using the flatMap combinator; I\'ve been following this discussion:
http:/
You also have a good example of concurrent Future
execution in "Scala notes – Futures – 3 (Combinators and Async)" from Arun Manivannan.
Our
Futures
need to run in parallel.
In order to achieve this, all we need to do is to extract theFuture
block out and declare them separately.
Code:
val oneFuture: Future[Int] = Future {
Thread.sleep(1000)
1
}
val twoFuture: Future[Int] = Future {
Thread.sleep(2000)
2
}
val threeFuture: Future[Int] = Future {
Thread.sleep(3000)
3
}
for-comprehension:
def sumOfThreeNumbersParallelMapForComprehension(): Future[Int] = for {
oneValue <- oneFuture
twoValue <- twoFuture
threeValue <- threeFuture
} yield oneValue + twoValue + threeValue
flatmap:
def sumOfThreeNumbersParallelMap(): Future[Int] = oneFuture.flatMap { oneValue =>
twoFuture.flatMap { twoValue =>
threeFuture.map { threeValue =>
oneValue + twoValue + threeValue
}
}
}
Test:
describe("Futures that are executed in parallel") {
it("could be composed using for comprehensions") {
val futureCombinators = new FutureCombinators
val result = timed(Await.result(futureCombinators.sumOfThreeNumbersParallel(), 4 seconds))
result shouldBe 6
}
}
It does illustrate that:
Future
is a container of a value(s) of some type (i.e it accepts a type as an argument and it can’t exist without it).
You can have aFuture[Int]
orFuture[String]
orFuture[AwesomeClass]
– you can’t just have a plainFuture
.
A fancy term for this is type-constructor.
To compare, aList
is a type constructor (and a Monad as well).
AList
is a container of values that are of typeInt,
String
or any of other types. AList
/Future
without a contained type does not exist.Future
hasflatMap
andunit
functions (and consequentially amap
function too).