Search code examples
scalascala-cats

Convert EitherT[Future, A, Future[B]] to EitherT[Future, A, B]


I am trying to change an EitherT[Future, A, B] to EitherT[Future, C, D] and for this, I am using bimap to map left and right parts appropriately. While I am transforming the right part of this EitherT, I am making a service call which returns me a Future[D]… I am having trouble converting this Future[D] to D in my bimap. Not sure how to proceed now. Any help here would be appreciated.

Psuedo code:

val myResult: EitherT[Future, C, D] = EitherT[Future, A, B](myService.doStuff())
    .bimap({ err => /*deal with errors and give me C*/ }
      ,{ success => someService.doSomething(success) // This is returing a Future[D]. But I want a D 
       })

Solution

  • Try .flatMap aka for-comprehension

    import cats.data.EitherT
    import cats.instances.future._
    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits.global
    
    val myResult: EitherT[Future, C, D] = for {
      d <- EitherT.right(someService.doSomething())
      res <- EitherT[Future, A, B](myService.doStuff())
        .bimap({ err => ??? : C //deal with errors and give me C
        }, { success => {
          d
        }
        })
    } yield res
    

    Try .biSemiflatMap

    val myResult: EitherT[Future, C, D] =
      EitherT[Future, A, B](myService.doStuff())
        .biSemiflatMap({ err => Future.successful(??? : C)
        }, { success => {
          someService.doSomething(success)
        }
        })