Scala Futures如何与flatMap链接在一起? [英] How are Scala Futures chained together with flatMap?
问题描述
我正在Scala中首次使用Futures,并且正在研究一个使用flatMap组合器的示例.我一直在关注这个讨论:
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
具体来说,此示例:
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")
}
被翻译为:
val purchase = usdQuote flatMap {
usd =>
chfQuote
.withFilter(chf => isProfitable(usd, chf))
.map(chf => connection.buy(amount, chf))
}
我要解决的麻烦是,如何以及何时执行flatMap?
What I'm having a bit of trouble grasping is how and when this is flatMap executed?
我了解到usdQuote和chfQuote由某个时间"的某个线程"执行,并且调用了它们的注册回调函数,问题是:
I understand that usdQuote and chfQuote are executed by "some thread" at "some time" and their registered callback functions called, questions are:
a)usdQuote和chfQuote是否同时执行? (我很确定他们是.)
a) Are usdQuote and chfQuote executed concurrently? (I'm pretty sure they are).
b)flatMap如何将Future useQuote的值分配给usd?像这样,当usdQuote操作完成时是否会调用它?
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)哪个线程正在执行"flatMap"和"map"操作(可能是最后一个问题的后续内容).
c) What thread is executing the 'flatMap' and 'map' operation (probably more of a follow-on from the last question).
干杯.
推荐答案
-
a)创建它们时,您已经开始针对范围内的隐式ExecutionContext执行它们,因此它们可能会同时运行,这取决于它的执行方式.
a) When you created them you've already started them executing against the implicit ExecutionContext in scope, so they're potentially running concurrently as it depends on how that is executing them.
b)并没有真正分配值,但是实现使用onComplete方法来使传递给您的函数在达到结果后被触发.目前,这应该链接到我指的那个flatMap方法:
b) It doesn't really assign the value as such, but the implementation uses the onComplete method to cause the function you've passed to be triggered once a result has been reached. At the current time this should link to that flatMap method I'm referring to: https://github.com/scala/scala/blob/v2.11.2/src/library/scala/concurrent/Future.scala#L246
c)它们是通过前面提到的ExecutionContext运行的,还要考虑一下,如果那些Future实例可以在不同的ExecutionContexts上运行,那么部分理解可以在不同的线程池上运行.
c) Those are running via the ExecutionContext previously mentioned, consider also that if those Future instances can be running on different ExecutionContexts, so parts of the for-comprehension can be running on different thread pools.
这篇关于Scala Futures如何与flatMap链接在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!