如何使用IO Monad退出全面理解

时间:2019-04-13 18:09:35

标签: scala io cats-effect

我想在用户输入“停止”并使readLn异步时进行无限制的退出读取打印循环。

import cats.effect.{ExitCode, IO, IOApp, Timer}

import scala.concurrent.duration._
import scala.io.StdIn
import scala.language.postfixOps
import cats.implicits._

object ReadWrite extends IOApp {
  val readLn: IO[String] = IO(StdIn.readLine())
  val readWriteName: IO[Nothing] = for {
    _     <- IO(println("write your name: "))
    name  <- readLn
    _     <- IO(println(s"Hello, $name"))
    t     <- name match {
      case "stop" => ???
      case _      =>  readWriteName
    }
  } yield t

  def run(args: List[String]): IO[ExitCode] =
    for {
      _ <- (Timer[IO].sleep(1 millisecond) *> readWriteName).start
      _ <- Timer[IO].sleep(100 second)
    } yield ExitCode.Success
}

我尝试使用IO(println(s"Buy Buy")),但出现错误消息:

Error:(20, 11) type mismatch;
 found   : t.type (with underlying type Unit)
 required: Nothing
  } yield t

如何正确退出?

我还想在另一个线程(例如readLn)中执行IO。

1 个答案:

答案 0 :(得分:3)

readWriteName的类型更改为IO[Unit]

val readWriteName: IO[Unit] = for {
  _     <- IO(println("write your name: "))
  name  <- readLn
  _     <- IO(println(s"Hello, $name"))
  t     <- name match {
    case "stop" => IO(println(s"Buy Buy"))
    case _      =>  readWriteName
  }
} yield t

关于线程,请查看Cats-effect and asynchronous IO specifics


尝试

  val readWriteName: IO[String] = for {
    _     <- IO(println("write your name: "))
    name  <- readLn
    _     <- IO(println(s"Hello, $name"))
    _     <- name match {
      case "stop" => IO(println(s"Buy Buy"))
      case _      =>  readWriteName
    }
  } yield name