Как выйти из For-Compression с IO Monad - PullRequest
2 голосов
/ 13 апреля 2019

Я хочу сделать бесконечный цикл печати с выходом, когда пользователь вводит «стоп» и делает 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

Как сделать выход без ошибки?

Также я хочу выполнить IO в другом потоке, например readLn.

1 Ответ

4 голосов
/ 13 апреля 2019

Изменить тип 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-эффекта и асинхронного ввода-вывода


Попробуйте

  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
...