【问题标题】:Find difference between two Future[Int] in Scala在 Scala 中查找两个 Future[Int] 之间的区别
【发布时间】:2021-09-05 21:54:09
【问题描述】:

我是 Scala 和 Futures 的新手。我的场景如下 -

val futureTotalCount : Future[Int]
val futureProcessedCount : Future[Int]

//I need to find the difference of above two futures to get unProcessedCount, something like-
val futureUnProcessedCount : Future[Int] = (futureTotalCount - futureProcessedCount)

这样的事情在 Scala 中是否可行?

【问题讨论】:

  • 你可能想做一些关于期货和 Scala 的基本教程/课程。
  • 我正在这样做,但我有一个紧急提交,所以我需要快速的东西。谢谢。

标签: scala future


【解决方案1】:

尝试以下方法:

val futureTotalCount: Future[Int] = Future(2)
val futureProcessedCount: Future[Int] = Future(1)
    
val futureResultCount: Future[Int] = for{
  totalCount <- futureTotalCount
  processedCount <- futureProcessedCount 
} yield (totalCount - processedCount)

// Or:
val futureResultCount = futureTotalCount.flatMap { totalCount =>
  futureProcessedCount.map { processedCount =>
    totalCount - processedCount
  }
}

【讨论】:

    【解决方案2】:
    futureTotalCount zip futureProcessedCount map { case(a,b) => a -  b }
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2014-09-29
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多