Created
September 27, 2024 21:16
-
-
Save fancellu/45e95a4d51c4045d14f22b9e8a03dc60 to your computer and use it in GitHub Desktop.
InterruptableReadLine ZIO example of a readLine that can be timedout
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 => SConsole } | |
import scala.io.StdIn | |
import java.io.{ BufferedReader, IOException } | |
import scala.util.Try | |
object InterruptableReadLine 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 now want to buy $value") | |
case None => Console.printLine("Timed out, no input provided for question.") | |
} | |
} yield () | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
Going to the grocery store
Timed out, no input provided for question.