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

后端 未结 3 1509
栀梦
栀梦 2020-12-09 21:56

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]]? I

相关标签:
3条回答
  • 2020-12-09 22:33

    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.

    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.

    0 讨论(0)
  • 2020-12-09 22:45

    I don't think you would want to do this anyway. Akka 2.0.5's docs show this for 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]. 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].

    //in scala.concurrent.Future:
    abstract def onComplete[U]
      (func: (Try[T]) ⇒ U)(implicit executor: ExecutionContext): Unit
    
    0 讨论(0)
  • 2020-12-09 22:55

    Another version of such conversion (in standard Scala):

    f.transform(tryResult => Success(tryResult.toEither))
    
    0 讨论(0)
提交回复
热议问题