如何执行效果列表?

问题描述

我有一个这种类型的值:

val effects : List[EitherT[Future,Error,Foo]] = ...

如何遍历列表并执行这些效果?我做过

effects.traverse

但该方法并未为该类型定义。

解决方法

正如评论中提到的,当您声明一些效果列表并希望执行它们并将效果收集到一个列表中时,最好去掉 Future。最好使用 IO 或其他惰性评估效果。

因此,如果您只需要在 traverseFuture[List[A]]

import cats.data.EitherT
import scala.concurrent.{ExecutionContext,Future}
import cats.syntax.traverse._
import cats.instances.list._
import cats.instances.future._

implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.global

case class Foo()
val effects : List[EitherT[Future,Error,Foo]] = ???
def f(e: EitherT[Future,Foo]): Future[Either[Error,Foo]] = ???
val result: Future[List[Either[Error,Foo]]] = effects.traverse(f)

此代码可编译,您只需要实现 f。您需要添加 import cats.instances.future._ 才能在 Furure 中具有遍历功能。

但更好的方法是在诸如 IO 之类的东西上构建您的流程:

import cats.data.EitherT
import cats.syntax.traverse._
import cats.instances.list._
import cats.effect.IO
val effects : List[EitherT[IO,Foo]] = ???
def f(e: EitherT[IO,Foo]): IO[Either[Error,Foo]] = ???
val result: IO[List[Either[Error,Foo]]] = effects.traverse(f)

并使用 unsafeRunAsync 调用它。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...