Scala 利用猫效应中的移位函数
我试图使用cats effect shift函数来异步运行代码 功能实现:Scala 利用猫效应中的移位函数,scala,scala-cats,Scala,Scala Cats,我试图使用cats effect shift函数来异步运行代码 功能实现: def asyncSendMsg(producer: KkProducer)(record: KkRecord) : IO[Either[String, RecordMetadata]] = for { res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main) } yield(res) def t
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())
}
}
def asyncSendMsg(生产者:kkkproducer)(记录:KkRecord):IO[String,RecordMetadata]]=
为了{
res Left(如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
[error]/home/developer/Desktop/scala/PureProducer/src/main/scala/TheProducer.scala:51:43:value shift不是cats.effect.IO的成员[String,org.apache.kafka.clients.producer.RecordMetadata]]
[错误]resIO.shift
是在IO
的伴生对象上定义的(API在不同版本的CAT之间发生了更改),在调用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()
@零编码当unsafeRunSync()
返回时,您回到main
。并将另一个线程的计算值分配给主线程中的变量?@zero\u编码unsafeRunSync
将执行此操作。
main
pool-1-thread-1