简体   繁体   English

将Akka的未来[A]转换为未来[要么[例外,A]]

[英]converting Akka's Future[A] to Future[Either[Exception,A]]

Is there a method in Akka (or in the standard library in Scala 2.10) to convert a Future[A] which might fail into a Future[Either[Exception,A]] ? 在Akka(或Scala 2.10中的标准库)中是否存在将Future[A]转换为Future[Either[Exception,A]] I know that you can write 我知道你可以写

f.map(Right(_)).recover {
  case e:Exception => Left(e)
}

It just seems to be such a common task that I wonder whether I have overlooked something. 这似乎是一个如此常见的任务,我想知道我是否忽略了一些东西。 I'm interested in answers for Scala 2.9/Akka and Scala 2.10. 我对Scala 2.9 / Akka和Scala 2.10的答案很感兴趣。

The primary reason why this method is missing is that it does not really have good semantics: the static type Future[Either[Throwable, T]] does not ensure that that future cannot fail, hence the type change does not gain you much in general. 缺少此方法的主要原因是它没有真正具有良好的语义:静态类型Future[Either[Throwable, T]]不能确保未来不会失败,因此类型更改通常不会让您获得太多。

It can of course make sense if you control all the code which handles those futures, and in that case it is trivial to add it yourself (the name is due to me posting before first coffee, feel free to replace with something better): 如果您控制处理这些未来的所有代码当然是有道理的,在这种情况下,自己添加它是微不足道的(这个名称是由于我在第一次喝咖啡之前发布的,可以随意用更好的东西替换):

implicit class FutureOps[T](val f: Future[T]) extends AnyVal {
  def lift(implicit ec: ExecutionContext): Future[Either[Throwable,T]] = {
    val p = promise[Either[Throwable,T]]()
    f.onComplete {
      case Success(s)  => p success Right(s)
      case Failure(ex) => p success Left(ex)
    }
    p.future
  }
}

It works very similarly with Akka 2.0 futures, hence I leave that exercise to the reader. 它与Akka 2.0期货非常相似,因此我将这个练习留给了读者。

此类转换的另一个版本(在标准Scala中):

f.transform(tryResult => Success(tryResult.toEither))

I don't think you would want to do this anyway. 无论如何,我认为你不想这样做。 Akka 2.0.5's docs show this for akka.dispatch.Future : Akka 2.0.5的文档显示了这个用于akka.dispatch.Future

abstract def onComplete[U](func: (Either[Throwable, T]) ⇒ U): Future.this.type

So the information that the Future might fail is already embedded into the behavior of a Future[T] . 因此,Future可能失败的信息已经嵌入到Future[T]的行为中。 The same applies with Scala 2.10's futures, where a future can complete as a Try[T] which is similar in purpose to an Either[Exception, T] . 这同样适用于Scala 2.10的未来,未来可以作为Try[T]完成,其目的与Either[Exception, T]

//in scala.concurrent.Future:
abstract def onComplete[U]
  (func: (Try[T]) ⇒ U)(implicit executor: ExecutionContext): Unit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM