无法转移其他线程池上的IO

时间:2018-09-11 17:15:58

标签: scala scala-cats

我正在阅读有关猫效果的教程

https://typelevel.org/blog/2017/05/02/io-monad-for-cats.html

根据本教程,我编写了这段代码

import scala.concurrent.ExecutionContext
import java.util.concurrent.Executors
import cats.effect.IO

val Main = ExecutionContext.global
val BlockingIO = ExecutionContext.fromExecutor(Executors.newCachedThreadPool())

val program = for {
_ <- IO { println("what is your name") }
name <- IO { readLine() }.shift(BlockingIO).shift(Main)
} yield s"Hello $name"
val output = program.unsafeRunSync
println(output)

我收到错误value shift is not a member of cats.effect.IO[String]

本教程如何转移readLines函数的结果

lines <- readLines("names.txt").shift(BlockingFileIO).shift(Main)

此示例的最终整体效果是readLine的块发生在我的BlockingIO池中。

1 个答案:

答案 0 :(得分:1)

好。我自己找到了答案。我认为该教程过时了

https://typelevel.org/cats-effect/datatypes/io.html

val program = for {
  _ <- IO { println("what is your name") }
  _ <- IO.shift(BlockingIO)
  name <- IO { readLine }
  _ <- IO.shift(Main)
} yield s"Hello $name"