对于一个大的List[Int]
,我决定使用List#grouped(Int)
来获得List[List[Int]]
。然后,我在上面映射,应用一个函数List[Int] => Future[List[Int]]
。我的意图是将一项职能同时适用于分名单。
现在我有List[scala.concurrent.Future[List[Int]]]
。
鉴于这种类型,我希望使用List[Int]
来收集结果。
做那件事的惯用方法是什么?
我假设你指的是Future[List[Int]]
,而不仅仅是List[Int]
。在这种情况下,您将使用Future.sequence
将List[Future[A]]
映射到Future[List[A]]
,然后使用flatten
映射单个Future
中包含的List
。
val list: List[Future[List[Int]]] = ...
Future.sequence(list).map(_.flatten)
如果出于某种原因只想删除Future
,那么你需要阻止才能获得它
Await.result(Future.sequence(list).map(_.flatten), Duration.Inf)
@m-z建议的sequence
方法会起作用,但最酷/惯用的方法是使用scalaz的traverseM
,而不是带有以下函数的map
:
def myFunction(li: List[Int]): Future[List[Int]] = ...
val myList: List[List[Int]] = ...
import scalaz._, Scalaz._
myList.traverseM(myFunction) //returns a Future[List[Int]]
val futures = List[Future[List[Int]]]
Future.fold(futures)(List.empty) { (l, r) =>
l ++ r
} onComplete {
case Success(r) => println(r)
case Failure(e) => e.printStackTrace()
}