Scala Futures如何与flatMap链接在一起? [英] How are Scala Futures chained together with flatMap?

查看:81
本文介绍了Scala Futures如何与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).

干杯.

推荐答案

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆