How to get Future[Right] from Future[Either[Left, Right]] in Scala?

1.3k Views Asked by At

I have two methods that already exist:

def methodB(): Future[Either[Error, Value]]




def methodC(futureValue: Future[Value]): Future[Value]

And I need a method that will get a result from methodB and put right value to methodC but it should be Future:

def methodA(): Future[Either[Error, Value]] = {
    val resultFromB: Future[Either[Error, Value]] = methodB()
    // get Future[Value] from resultFromB and put it to methodC

    resultFromB
  }

Could you please help? Maybe how to convert Future[Either[Error, Value]] to Either[Future[Error], Future[Value]] ?

4

There are 4 best solutions below

0
On

Getting Future[Value] from Future[Either[Error, Value]] is straightforward, though you need a default value in case it is Left rather than Right:

val default: Value = ???
val res: Future[Value] = resultFromB.map(_.getOrElse(default))

Converting Future[Either[Error, Value]] to Either[Future[Error], Future[Value]] is pointless, because you cannot decide if the outer Either is Left or Right until the original Future is complete, in which case there is no point in making the inner values Futures.

0
On

Since Future can fail, you coud write:

def fright[A,B](fab: Future[Either[A,B]]): Future[B] = 
  fab.flatMap(ab => ab.fold(b => Future.failed(new Throwable("t'was left")), b => Future(b)))
0
On

As Future have failure and success cases corresponding to Either's Left and Right, you can simply use -

methodB() flatMap {
    case Left(ex) => Future.failed(ex)
    case Right(v) => Future.successful(v)
}

This will return you Future[Value]

0
On

As a supplement to other answers, if you are using cats and Error is a subclass of Throwable you could just use rethrow:

import cats.implicits._


val result: Future[Value] = resultFromB.rethrow