当我们想并行执行3 IO时,这是一个例子。
def test: Unit = {
val ioA = IO.shift *> IO(println("Running ioA"))
// ioA: cats.effect.IO[Unit] = <function1>
val ioB = IO.shift *> IO(println("Running ioB"))
// ioB: cats.effect.IO[Unit] = <function1>
val ioC = IO.shift *> IO(println("Running ioC"))
// ioC: cats.effect.IO[Unit] = <function1>
val program: IO[Unit] = (ioA, ioB, ioC).parMapN { (_, _, _) => () }
// program: cats.effect.IO[Unit] = <function1>
program.unsafeRunSync()
}第一个问题:如果在本例中使用IO.shift的意义是什么?
第二个问题:如果我们有一个List of IO,我们想并行执行怎么办?我已经为这个任务创建了一个函数,但是我不知道这个东西是否已经存在于库中
def parallelize(ios: List[IO[Unit]]): IO[Unit] = {
ios.foldLeft(IO.pure(())) { case (currentResult, currentItem) =>
(currentResult, currentItem).parMapN((_, _) => ())
}
}发布于 2018-04-20 08:49:39
这适用于“猫-核心:1.1.0”和“猫-效果:0.10.1”。
import cats.instances.list._
import cats.syntax.parallel._
//ios: List[IO[A]]
ios.parSequence //IO[List[A]]https://stackoverflow.com/questions/49857581
复制相似问题