将EitherT [Future,A,Future [B]]转换为EitherT [Future,A,B]

时间:2019-08-21 19:20:47

标签: scala scala-cats

我正在尝试将EitherT[Future, A, B]更改为EitherT[Future, C, D],为此,我正在使用bimap适当地映射左右部分。 当我转换此EitherT的正确部分时,我正在进行服务调用,该返回给我一个Future[D]……在我将Future[D]转换为D时遇到麻烦bimap。不确定现在如何进行。任何帮助,我们将不胜感激。

伪代码:

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 
       })

1 个答案:

答案 0 :(得分:2)

尝试.flatMap又称for理解

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

尝试.biSemiflatMap

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