使用来自猫效果的移位功能

时间:2017-11-13 13:25:23

标签: scala scala-cats

我正在尝试使用cat effect shift函数来异步运行代码。

功能实现:

  def asyncSendMsg(producer: KkProducer)(record: KkRecord) : IO[Either[String, RecordMetadata]] =
    for {
      res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main)
    } yield(res)

  def trySendMsg(producer: KkProducer)(record: KkRecord): IO[Either[String, RecordMetadata]] =
    IO {
      try {
        Right(producer.send(record).get())
      } catch {
        case e: Exception => Left(e.getMessage())
      }
    }

尝试编译,我收到:

[error] /home/developer/Desktop/scala/PureProducer/src/main/scala/TheProducer.scala:51:43: value shift is not a member of cats.effect.IO[Either[String,org.apache.kafka.clients.producer.RecordMetadata]]
[error]       res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main)
[error]                                           ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Nov 13, 2017 2:18:06 PM

我必须导入哪个库才能使用shift功能?

1 个答案:

答案 0 :(得分:3)

IO.shiftIO的伴随对象上定义(API在猫的版本之间已经更改),您可以在调用IO调用之前将其用于理解:

val nonBlockingExecContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))

val res = for {
  _ <- IO { println(Thread.currentThread().getName) }
  _ <- IO.shift(nonBlockingExecContext)
  _ <- IO { println(Thread.currentThread().getName) }
} yield ()

res.unsafeRunSync()

收率:

main
pool-1-thread-1