【发布时间】:2019-09-01 17:50:21
【问题描述】:
我正在使用for 并行运行 2 个期货。我想知道在所有情况下哪个成功,哪个失败(都应该运行直到完成,结果或失败状态)。目前我只能检索组合成功结果
我从这里进行了检查,但这还不够,因为当一个失败时我没有获得成功状态,也没有在两者都失败的情况下都失败failure in Scala future's for comprehension
case class TaggedException(context:String, val throwable: Throwable) extends Exception(throwable.getMessage)
val f1 = Future {...}.recoverWith {case e:Throwable => Future.Failed(new TaggedException("first one failed", e))}
val f2 = Future {...}.recoverWith {case e: Throwable => Future.Failed(new TaggedException("second one failed", e))}
val combinedResult = for {
r1 <- f1
r2 <- f2
} yield (r1,r2)
combinedResult.onFailure {
case e : TaggedException => ... // if both fail I only get the first line in the for
// in case where single fails I only know fail status without the success of the second
}
我正在努力避免这种混乱:
var countCompleted = 0 ... or some other atomic way to count
f1 onComplete {
case Success(value) => {
... countCompleted increment ...
// handle success
if both completed {
// handle returning a status
}
}
case Failure(error) => {
... countCompleted increment ...
// handle failure
if both completed {
// handle returning a status
}
}
}
f2 onComplete {
case Success(value) => {
... countCompleted increment ...
// handle success
if both completed {
// handle returning a status
}
}
case Failure(error) => {
... countCompleted increment ...
// handle failure
if both completed {
// handle returning a status
}
}
}
编辑:另一个版本 - 这是一种有效的方法吗?
def toFutureTry[A](future: Future[A]):Future[Try[A]] = future.map(Success(_)).recover {case t: Throwable => Failure(t)}
val fa: Future[Try[Blah]] = toFutureTry(f1)
val fb: Future[Try[Foo]] = toFutureTry(f2)
val combinedRes = for {
ra <- fa
rb <- fb
} yield (ra,rb)
combinedRes.onComplete {
case Success(successRes: (Try[Blah], Try[Foo])) => // all of these cases are success or fails
case Failure(f: Throwable) => // i think it is unused right?
}
【问题讨论】: