Either[A, Future[B]] to Future[Either[A, B]]
Not sure there's an out of the box solution, this is what I came up with:
def foldEitherOfFuture[A, B](e: Either[A, Future[B]]): Future[Either[A, B]] =
e match {
case Left(s) => Future.successful(Left(s))
case Right(f) => f.map(Right(_))
}
In addition to catch eventual exception from the Future
you can add a recover
and map it to a Left
:
case Right(f) => f.map(Right(_)).recover { case _ => Left(/** some error*/) }
There is no api functional call to do that. I'd try something like this:
def getResult[A, B]: Either[A, Future[B]] = ???
val res = getResult.fold(fa = l => Future(Left(l)), fb = r => r.map(value => Right(value)))
If you're using scalaz, you can just use sequenceU
import scala.concurrent.ExecutionContext.Implicits.global
import scalaz._
import Scalaz._
val x: Either[String, Future[Int]] = ???
val y: Future[Either[String, Int]] = x.sequenceU
Update (August 2019):
If you're using cats, use sequence
:
import cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
val x: Either[String, Future[Int]] = ???
val y: Future[Either[String, Int]] = x.sequence