描绘成功与失败的未来 [英] Map a Future for both Success and Failure

查看:43
本文介绍了描绘成功与失败的未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Future [T],我想将结果映射为成功和失败.

I have a Future[T] and I want to map the result, on both success and failure.

例如,类似

val future = ... // Future[T]
val mapped = future.mapAll { 
  case Success(a) => "OK"
  case Failure(e) => "KO"
}

如果我使用mapflatmap,它将仅映射成功的期货.如果使用recover,它将仅映射失败的期货. onComplete执行回调,但不返回修改后的Future. Transform可以工作,但是需要2个功能而不是部分功能,所以有点难看.

If I use map or flatmap, it will only map successes futures. If I use recover, it will only map failed futures. onComplete executes a callback but does not return a modified future. Transform will work, but takes 2 functions rather than a partial function, so is a bit uglier.

我知道我可以制作一个新的Promise,并使用onCompleteonSuccess/onFailure完成该操作,但是我希望我缺少一些可以使我完成上述任务的内容单个PF.

I know I could make a new Promise, and complete that with onComplete or onSuccess/onFailure, but I was hoping there was something I was missing that would allow me to do the above with a single PF.

推荐答案

编辑2017-09-18:从Scala 2.12开始,有一个transform方法采用Try[T] => Try[S].这样你就可以写

Edit 2017-09-18: As of Scala 2.12, there is a transform method that takes a Try[T] => Try[S]. So you can write

val future = ... // Future[T]
val mapped = future.transform {
  case Success(_) => Success("OK")
  case Failure(_) => Success("KO")
}

对于2.11.x,以下内容仍然适用:

For 2.11.x, the below still applies:

AFAIK,您不能直接使用单个PF来执行此操作.并且transform转换Throwable => Throwable,因此也无济于事.您可以立即使用的最接近的产品:

AFAIK, you can't do this directly with a single PF. And transform transforms Throwable => Throwable, so that won't help you either. The closest you can get out of the box:

val mapped: Future[String] = future.map(_ => "OK").recover{case _ => "KO"}

也就是说,实现mapAll很简单:

That said, implementing your mapAll is trivial:

implicit class RichFuture[T](f: Future[T]) {
  def mapAll[U](pf: PartialFunction[Try[T], U]): Future[U] = {
    val p = Promise[U]()
    f.onComplete(r => p.complete(Try(pf(r))))
    p.future
  }
}

这篇关于描绘成功与失败的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆