Scala: List[Future] to Future[List] disregarding failed futures

前端 未结 6 583
终归单人心
终归单人心 2020-11-29 16:28

I\'m looking for a way to convert an arbitrary length list of Futures to a Future of List. I\'m using Playframework, so ultimately, what I really want is a Future[Resu

6条回答
  •  半阙折子戏
    2020-11-29 16:53

    I just came across this question and have another solution to offer:

    def allSuccessful[A, M[X] <: TraversableOnce[X]](in: M[Future[A]])
                                                    (implicit cbf: CanBuildFrom[M[Future[A]], A, M[A]], 
                                                     executor: ExecutionContext): Future[M[A]] = {
        in.foldLeft(Future.successful(cbf(in))) {
          (fr, fa) ⇒ (for (r ← fr; a ← fa) yield r += a) fallbackTo fr
        } map (_.result())
    }
    

    The idea here is that within the fold you are waiting for the next element in the list to complete (using the for-comprehension syntax) and if the next one fails you just fallback to what you already have.

提交回复
热议问题