Scala期货 - flatMap和onFailure

时间:2015-05-11 13:57:41

标签: scala monads future

如果我有一些计算需要一段时间,我可能会把它放在scala.concurrent.Future

val f = Future { someLongRunningFunction() }

并且假设我想在计算完成后异步执行其他操作:

f.flatMap{ _ => anotherLongRunningFunction() }

如果f的初始阻止失败,我该如何"惯用"使用flatMap或其他组合器时处理此问题?仅仅是在recover之前使用onFailureflatMap的情况吗?

我喜欢使用flatMap的优雅和简洁,但似乎失败的情况会妨碍它。

编辑:第二个未来依赖于第一个,因此flatMap。我正在寻找一种优雅的解决方案,让我像flatMap那样链接,但也处理第一次的失败。

2 个答案:

答案 0 :(得分:3)

如果你有几个未来,你可以把它们放在一起进行理解。

val futureResult = for {
    result1 <- future1
    result2 <- future2
    ...
} yield {
    //computation with results
}

您可以在最后添加recover,以防您想要处理任何可能发现的异常:

futureResult.recover{
    case exceptionResult: Throwable => // Process exception
}

我认为使用flatMap更加干净。

答案 1 :(得分:1)

I'm only starting with Future, but here are some ideas. If you really want to use flatMap, you have to turn the failure into a success. for{ a <- f recover r b <- another(a) } yield b This works if the return type of r is :> the result type of f. Or you can pass the problem of what to do with the failure on to the next process for{ a <- f map (x => Success(x)) recover (ex => Failure(ex)) b <- another(a) } yield b Here the argument type of another would be Try[T] where the type of f is Future[T].