了解IO monad

St.*_*rio 7 functional-programming scala scala-cats

我试图通过cats.effect.IO例子来理解异步计算并得到一些误解.该unsafe方法unsafeRunAsync似乎异步运行底层效果(我希望ContextShift提供一些).但该方法看起来像这样:

final def unsafeRunAsync(cb: Either[Throwable, A] => Unit): Unit =
  IORunLoop.start(this, cb)
Run Code Online (Sandbox Code Playgroud)

既没有ContextShift也没有ExecutionContext提供.这是一个非常简单的例子:

object TestIo extends App {
  println(s"Main thread = ${Thread.currentThread().getName}")
  val io = IO {
    println(s"Effect thread = ${Thread.currentThread().getName}")
    Thread.sleep(1000)
  }
  io.unsafeRunAsync(_ => println(s"Callback thread = ${Thread.currentThread().getName}"))
  println(s"Finished")
}
Run Code Online (Sandbox Code Playgroud)

输出是

Main thread = main
Effect thread = main
Callback thread = main
Finished
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这里的所有内容都是在主线程中 同步运行的.你能解释一下unsafeRunAsync吗?对我而言似乎是一样的unsafeRunSync.

pme*_*pme 4

关于

未提供 ContextShift 和 ExecutionContext。

有一个上下文切换cats.effect.IO

请参阅此博客:https://www.jaspervanzandbeek.com/scala/cats-io-monad/

这里有一个例子:

def blockingOperation(): String = {
  // Read from file
  ...
}

val result: IO[String] = for {
  _ <- IO.shift(executionContextForBlockingOperations)
  result <- IO { blockingOperation() }
  _ <- IO.shift(mainExecutionContext)
} yield result
Run Code Online (Sandbox Code Playgroud)