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

前端 未结 6 585
终归单人心
终归单人心 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:52

    Scala 2.12 has an improvement on Future.transform that lends itself in an anwser with less codes.

    val futures = Seq(Future{1},Future{throw new Exception})
    
    // instead of `map` and `recover`, use `transform`
    val seq = Future.sequence(futures.map(_.transform(Success(_)))) 
    
    val successes = seq.map(_.collect{case Success(x)=>x})
    successes
    //res1: Future[Seq[Int]] = Future(Success(List(1)))
    
    val failures = seq.map(_.collect{case Failure(x)=>x})
    failures
    //res2: Future[Seq[Throwable]] = Future(Success(List(java.lang.Exception)))
    

提交回复
热议问题