在 Scala 中找出两个 Future[Int] 之间的区别

Find difference between two Future[Int] in Scala

我是 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 中可以实现这样的功能吗?

尝试以下操作:

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
  }
}
futureTotalCount zip futureProcessedCount map { case(a,b) => a -  b }