与 cats 并行压缩两个 EitherT[Future, _, _]

Aki*_*Aki 1 scala scala-cats

scala 中的常规 future 提供了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
Run Code Online (Sandbox Code Playgroud)

我希望sum是一个Right(30)whenab都是两个Right值。此外,与该Future.zip函数一样,两个 future 应该并行运行:

Dmy*_*tin 5

我猜你正在寻找应用程序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))))
Run Code Online (Sandbox Code Playgroud)