【问题标题】:Convert EitherT[Future, A, Future[B]] to EitherT[Future, A, B]将 EitherT[Future, A, Future[B]] 转换为 EitherT[Future, A, B]
【发布时间】:2019-08-21 19:20:47
【问题描述】:

我正在尝试将EitherT[Future, A, B] 更改为EitherT[Future, C, D],为此,我使用bimap 来适当地映射左右部分。 当我正在转换这个EitherT 的正确部分时,我正在拨打一个服务电话,它返回给我一个Future[D]……我无法在我的bimap 中将此Future[D] 转换为D。现在不知道如何进行。如有任何帮助,我们将不胜感激。

伪代码:

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

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    试试.flatMap又名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
    

    试试.biSemiflatMap

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

    【讨论】:

    • 天哪! someService.doSomething() 实际上应该是 someService.doSomething(success)。 :( 将相应地更新问题。
    • 不错!我能够使用您的第一个建议来解决这个问题!...非常感谢。出于某种原因,我找不到biSemiflatMap 可能是因为我使用的是旧版本的猫库。
    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多