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://docs.scala-lang.org/overviews/core/futures.html
Specifically, this example:
val usdQuote = future { connection.getCurrentValue(USD) }
val chfQuote = future { connection.getCurrentValue(CHF) }
val purchase = for {
usd <- usdQuote
chf <- chfQuote
if isProfitable(usd, chf)
} yield connection.buy(amount, chf)
purchase onSuccess {
case _ => println("Purchased " + amount + " CHF")
}
is translated to this:
val purchase = usdQuote flatMap {
usd =>
chfQuote
.withFilter(chf => isProfitable(usd, chf))
.map(chf => connection.buy(amount, chf))
}
What I'm having a bit of trouble grasping is how and when this is flatMap executed?
I understand that usdQuote and chfQuote are executed by "some thread" at "some time" and their registered callback functions called, questions are:
a) Are usdQuote and chfQuote executed concurrently? (I'm pretty sure they are).
b) How does flatMap assign the value of the Future useQuote to usd? As in, does it get called when the operation usdQuote completes?
c) What thread is executing the 'flatMap' and 'map' operation (probably more of a follow-on from the last question).
Cheers.