简体   繁体   中英

Either[A, Future[B]] to Future[Either[A, B]]

Is there a way to convert a

Either[A, Future[B]] 

to a

Future[Either[A, B]]

I have in mind something like the Future.sequence method which converts from a List[Future] to a Future[List]

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

Dumonad adds a set of extension methods to ease of reactive programming:

import io.github.dumonad.dumonad.Implicits._

val eitherOfFuture: Either[L,Future[R]]

val futureOfEither: Future[Either[L,R]] = eitherOfFuture.dummed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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