Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created September 27, 2024 21:16
Show Gist options
  • Save fancellu/45e95a4d51c4045d14f22b9e8a03dc60 to your computer and use it in GitHub Desktop.
Save fancellu/45e95a4d51c4045d14f22b9e8a03dc60 to your computer and use it in GitHub Desktop.
InterruptableReadLine ZIO example of a readLine that can be timedout
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 ()
}
@fancellu
Copy link
Author

Output

Going to the grocery store
Timed out, no input provided for question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment