仅计算一次共享scalaz任务

时间:2016-08-22 18:36:22

标签: scala task scalaz

我有以下类与任务(Scalaz):

case class Foo(priceHistory: Task[Vector[Double]], average: Task[Double])

average任务在其计算中运行priceHistory任务。我可以做什么,以便priceHistory在运行两个任务时不会计算两次?

average任务:

  Task({
    val prices = priceHistory.unsafePerformSync
    prices.foldLeft(0)((acc, p) => acc + p) / prices.length
  })

priceHistory任务:

Task(retrieveData(ticker, from, to))

示例电话:

average.unsafePerformSync // Internally runs priceHistory task
priceHistory.unsafePerformSync // Shouldn't have to be re-run...

1 个答案:

答案 0 :(得分:1)

将您的价格历史记录放入monad,然后在您运行任务时对其进行一次评估。

  case class Foo(priceHistory: Vector[Double], average: Double)
  val priceHistoryTask: Task[Vector[Double]] = ??? 

  val fooTask: Task[Foo] = for {
    prices ← priceHistoryTask
    avg = prices.sum / prices.length
  } yield Foo(prices, avg)