首页 > 解决方案 > 与猫并行压缩两个 EitherT[Future, _, _]

问题描述

scala 中的常规期货提供zip操作员。当两者都成功并并行运行它们时,它将结合它们的值。猫有两个时是否有类似的东西EitherT[Future, _, _]


val a: EitherT[Future, String, Int] = EitherT.right(10)
val b: EitherT[Future, String, Int] = EitherT.right(20)
val sum: EitherT[Future, String, Int] = for ((a, b) <- a zip b) yield a + b

我希望sum成为一个Right(30)whenabare both Rightvalues。此外,与Future.zip函数一样,两个期货应该并行运行:

标签: scalascala-cats

解决方案


我猜你正在寻找应用程序mapN

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._
import cats.data.EitherT
import cats.instances.future._
import cats.syntax.apply._

val a: EitherT[Future, String, Int] = EitherT.right(Future(10))
val b: EitherT[Future, String, Int] = EitherT.right(Future(20))

val sum: EitherT[Future, String, Int] = (a, b).mapN(_ + _) // EitherT(Future(Success(Right(30))))

推荐阅读