并行执行`IO`的`List`

nam*_*nam 7 scala scala-cats

这是我们想要IO并行执行3的示例

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()
  }
Run Code Online (Sandbox Code Playgroud)

第一个问题:如果IO.shift在这个例子中使用点怎么办?

第二个问题:如果我们有一个ListIO,我们希望在并行执行?我已经为这个任务创建了一个函数但我不知道这个东西是否已经存在于库中

def parallelize(ios: List[IO[Unit]]): IO[Unit] = {
    ios.foldLeft(IO.pure(())) { case (currentResult, currentItem) =>
      (currentResult, currentItem).parMapN((_, _) => ())
    }
  }
Run Code Online (Sandbox Code Playgroud)

Lau*_*vas 5

这适用于“ cats-core:1.1.0”和“ cats-effect:0.10.1”

import cats.instances.list._
import cats.syntax.parallel._

//ios: List[IO[A]]
ios.parSequence //IO[List[A]]
Run Code Online (Sandbox Code Playgroud)