Skip to content

Instantly share code, notes, and snippets.

@calvinlfer
Created September 27, 2024 20:14
Show Gist options
  • Save calvinlfer/d1039fb5a69e11d542640ecf8989e014 to your computer and use it in GitHub Desktop.
Save calvinlfer/d1039fb5a69e11d542640ecf8989e014 to your computer and use it in GitHub Desktop.
An example of how to achieve an interruptible readLine with ZIO
import zio.*
import scala.Console as SConsole
import scala.io.StdIn
import java.io.{BufferedReader, IOException}
import scala.util.Try
object InterruptibleReadLineExample extends ZIOAppDefault {
def altReadLine(reader: BufferedReader = SConsole.in) =
ZIO
.sleep(200.millis)
.repeatUntil(_ => reader.ready()) *> (ZIO.fromTry(Try(StdIn.readLine()))).refineOrDie[IOException] {
case e: IOException => e
}
override val run =
for {
_ <- Console.printLine("Going to the grocery store")
input <- altReadLine().timeout(5.seconds)
_ <- input match {
case Some(value) => Console.printLine(s"You want to buy $value")
case None => Console.printLine("Timed out, no input provided.")
}
} yield ()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment