Scala:List[Future]到Future[List],忽略失败的Future

s4chpxco  于 2022-12-18  发布在  Scala
关注(0)|答案(7)|浏览(212)

我正在寻找一种方法来将任意长度的Futures列表转换为Future of List。我使用的是Playframework,所以最终,我真正想要的是一个Future[Result],但为了简化,我们就说Future[List[Int]]。正常的方法是使用Future.sequence(...),但有一个扭曲...我给出的列表通常有大约10-20个Futures在里面。并且这些future中的一个失败并不罕见(它们正在发出外部Web服务请求)。
在其中一个失败的情况下,我不需要重试所有这些命令,而是希望能够找到成功的命令并返回它们。
例如,执行以下操作无效:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) :: 
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure

我不想得到唯一的异常,我希望能够把1和3从那里拉出来。我尝试使用Future.fold,但显然这只是在幕后调用Future.sequence

fjaof16o

fjaof16o1#

诀窍是首先确保没有一个future失败。.recover在这里是您的朋友,您可以将它与map组合,将所有Future[T]结果转换为Future[Try[T]]]示例,所有这些示例都肯定是成功的future。

  • 注意:这里也可以使用OptionEither,但是如果您特别想要捕获异常,Try是最干净的方法 *
def futureToFutureTry[T](f: Future[T]): Future[Try[T]] =
  f.map(Success(_)).recover { case x => Failure(x)}

val listOfFutures = ...
val listOfFutureTrys = listOfFutures.map(futureToFutureTry(_))

然后像前面一样使用Future.sequence,给予Future[List[Try[T]]]

val futureListOfTrys = Future.sequence(listOfFutureTrys)

然后过滤:

val futureListOfSuccesses = futureListOfTrys.map(_.filter(_.isSuccess))


如果需要,您甚至可以提取特定的故障:

val futureListOfFailures = futureListOfTrys.map(_.filter(_.isFailure))
mbjcgjjk

mbjcgjjk2#

Scala 2.12对Future.transform进行了改进,使其能够使用更少的代码。

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)))
nhn9ugyo

nhn9ugyo3#

我尝试了Kevin的答案,但在我的Scala版本(2.11.5)上遇到了一个小故障......我更正了这个问题,如果有人感兴趣,我还编写了一些额外的测试......以下是我的版本〉

implicit class FutureCompanionOps(val f: Future.type) extends AnyVal {

    /** Given a list of futures `fs`, returns the future holding the list of Try's of the futures from `fs`.
      * The returned future is completed only once all of the futures in `fs` have been completed.
      */
    def allAsTrys[T](fItems: /* future items */ List[Future[T]]): Future[List[Try[T]]] = {
      val listOfFutureTrys: List[Future[Try[T]]] = fItems.map(futureToFutureTry)
      Future.sequence(listOfFutureTrys)
    }

    def futureToFutureTry[T](f: Future[T]): Future[Try[T]] = {
      f.map(Success(_)) .recover({case x => Failure(x)})
    }

    def allFailedAsTrys[T](fItems: /* future items */ List[Future[T]]): Future[List[Try[T]]] = {
      allAsTrys(fItems).map(_.filter(_.isFailure))
    }

    def allSucceededAsTrys[T](fItems: /* future items */ List[Future[T]]): Future[List[Try[T]]] = {
      allAsTrys(fItems).map(_.filter(_.isSuccess))
    }
}

// Tests... 


  // allAsTrys tests
  //
  test("futureToFutureTry returns Success if no exception") {
    val future =  Future.futureToFutureTry(Future{"mouse"})
    Thread.sleep(0, 100)
    val futureValue = future.value
    assert(futureValue == Some(Success(Success("mouse"))))
  }
  test("futureToFutureTry returns Failure if exception thrown") {
    val future =  Future.futureToFutureTry(Future{throw new IllegalStateException("bad news")})
    Thread.sleep(5)            // need to sleep a LOT longer to get Exception from failure case... interesting.....
    val futureValue = future.value

    assertResult(true) {
      futureValue match {
        case Some(Success(Failure(error: IllegalStateException)))  => true
      }
    }
  }
  test("Future.allAsTrys returns Nil given Nil list as input") {
    val future =  Future.allAsTrys(Nil)
    assert ( Await.result(future, 100 nanosecond).isEmpty )
  }
  test("Future.allAsTrys returns successful item even if preceded by failing item") {
    val future1 =  Future{throw new IllegalStateException("bad news")}
    var future2 = Future{"dog"}

    val futureListOfTrys =  Future.allAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys, 10 milli)
    System.out.println("successItem:" + listOfTrys);

    assert(listOfTrys(0).failed.get.getMessage.contains("bad news"))
    assert(listOfTrys(1) == Success("dog"))
  }
  test("Future.allAsTrys returns successful item even if followed by failing item") {
    var future1 = Future{"dog"}
    val future2 =  Future{throw new IllegalStateException("bad news")}

    val futureListOfTrys =  Future.allAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys,  10 milli)
    System.out.println("successItem:" + listOfTrys);

    assert(listOfTrys(1).failed.get.getMessage.contains("bad news"))
    assert(listOfTrys(0) == Success("dog"))
  }
  test("Future.allFailedAsTrys returns the failed item and only that item") {
    var future1 = Future{"dog"}
    val future2 =  Future{throw new IllegalStateException("bad news")}

    val futureListOfTrys =  Future.allFailedAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys,  10 milli)
    assert(listOfTrys(0).failed.get.getMessage.contains("bad news"))
    assert(listOfTrys.size == 1)
  }
  test("Future.allSucceededAsTrys returns the succeeded item and only that item") {
    var future1 = Future{"dog"}
    val future2 =  Future{throw new IllegalStateException("bad news")}

    val futureListOfTrys =  Future.allSucceededAsTrys(List(future1,future2))
    val listOfTrys =  Await.result(futureListOfTrys,  10 milli)
    assert(listOfTrys(0) == Success("dog"))
    assert(listOfTrys.size == 1)
  }
1qczuiv0

1qczuiv04#

我刚刚遇到这个问题,并有另一个解决方案提供:

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())
}

这里的想法是,在fold中,你等待列表中的下一个元素完成(使用for-comprehension语法),如果下一个元素失败,你就回退到你已经拥有的元素。

erhoui1w

erhoui1w5#

您可以轻松地将将来的结果与选项 Package 在一起,然后展开列表:

def futureToFutureOption[T](f: Future[T]): Future[Option[T]] =
    f.map(Some(_)).recover {
      case e => None
    }
val listOfFutureOptions = listOfFutures.map(futureToFutureOption(_))

val futureListOfOptions = Future.sequence(listOfFutureOptions)

val futureListOfSuccesses = futureListOfOptions.flatten
wmtdaxz3

wmtdaxz36#

您还可以在不同的列表中收集成功和不成功的结果:

def safeSequence[A](futures: List[Future[A]]): Future[(List[Throwable], List[A])] = {
  futures.foldLeft(Future.successful((List.empty[Throwable], List.empty[A]))) { (flist, future) =>
    flist.flatMap { case (elist, alist) =>
      future
        .map { success => (elist, alist :+ success) }
        .recover { case error: Throwable => (elist :+ error, alist) }
    }
  }
}
eimct9ow

eimct9ow7#

如果你因为某些原因需要保留失败的future,比如日志记录或条件处理,这可以在Scala 2.12+中使用,你可以在这里找到工作代码。

val f1 = Future(1)
val f2 = Future(2)
val ff = Future.failed(new Exception())

val futures: Seq[Future[Either[Throwable, Int]]] =
  Seq(f1, f2, ff).map(_.transform(f => Success(f.toEither)))

val sum = Future
  .sequence(futures)
  .map { eithers =>
    val (failures, successes) = eithers.partitionMap(identity)

    val fsum = failures.map(_ => 100).sum
    val ssum = successes.sum

    fsum + ssum
  }

assert(Await.result(sum, 1.second) == 103)

相关问题