简体   繁体   English

Scala:如何组合返回Future的方法

[英]Scala: How to combine methods that return a Future

Given a Map that stores exchange rates from EUR/USD to BTC... 给定一个存储从EUR / USD到BTC的汇率的Map ...

val btcRates = Map("EUR" -> 0.0036, "USD" -> 0.0045)

... and the following two methods... ...以及以下两种方法...

// returns a Future containing a Map of value to convert to BTC
def getAmounts = Future(Map("EUR" -> 500.0, "USD" -> 550.0, "CHF" -> 400))

// returns a Future containing the exchange rate for the specified currency
def getBtcRate(refCurrency: String) = Future(btcRates(refCurrency))

How do I invoke getAmounts and then for each element of the Map it returns invoke getBtcRate to convert the amount to BTC? 如何调用getAmounts ,然后为Map每个元素返回getBtcRate以将金额转换为BTC? And how do I sum all the converted amounts? 以及如何将所有转换后的金额相加?

def getTotal: Future[Double] = {
  getAmounts.flatMap { _.map { case (currency, amount) =>
    getBtcRate(currency).flatMap { rate =>
      amount * rate // how do I sum this and how do I return the result?
    }
  }}
}

I've used for-comprehension for getTotal since it's a little easier on the eyes than a chain of flatmap s: 我对getTotal使用了理解 ,因为它在眼中比flatmap容易一些:

  def getTotal: Future[Double] = for {
    amounts <- getAmounts
    totals <- Future.sequence(
      amounts.map { case (currency, amount) => 
        getBtcRate(currency).map(rate => amount * rate)
      }
    )
  } yield totals.sum

What this does is that amounts is the result of getAmounts (really this is the body of your flatmap ). 这是因为amountsgetAmounts的结果(实际上这是flatmap的主体)。 You then map over that tuple to create a sequence of futures by calling getBtcRate for each currency . 然后,通过为每种currency调用getBtcRate ,在该元组上映射以创建期货序列。 Each of those futures is then mapped to get the total. 然后,将这些期货中的每一个进行映射以获得总计。

Now you have a Iterable[Future[Double]] and using Future.sequence you transform it into a Future[Iterable[Double]] 现在您有了一个Iterable[Future[Double]]并使用Future.sequence将其转换为Future[Iterable[Double]]

Now you can just yield that Iterable and sum it, yielding the desired Future[Double] . 现在,您可以生成该Iterable并将其sum ,从而生成所需的Future[Double]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM