首页 > 解决方案 > 将 EitherT[Future, A, Future[B]] 转换为 EitherT[Future, A, B]

问题描述

我正在尝试更改EitherT[Future, A, B]toEitherT[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 
       })

标签: scalascala-cats

解决方案


尝试.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)
    }
    })

推荐阅读