Created
September 27, 2024 20:14
-
-
Save calvinlfer/d1039fb5a69e11d542640ecf8989e014 to your computer and use it in GitHub Desktop.
An example of how to achieve an interruptible readLine with ZIO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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