Skip to content

Instantly share code, notes, and snippets.

@kossal
Created July 24, 2021 21:39
Show Gist options
  • Save kossal/f5b33cbc6213f4e5b8ef40eb72519c7c to your computer and use it in GitHub Desktop.
Save kossal/f5b33cbc6213f4e5b8ef40eb72519c7c to your computer and use it in GitHub Desktop.
ZIO common methods
// succeed returns a succesful ZIO and fail a failing ZIO
ZIO.succeed("Hello"): Task[String]
ZIO.fail(new Throwable("Failed")): Task[String]
// Lift computations to ZIO
// Any failure will be captured as a Throwable
ZIO.effect(5 / 10): Task[Double]
// Lift effects that don't fail
ZIO.effectTotal(println("This should not fail")): UIO[Unit]
// map let's you transform the return value of a ZIO
val inputLenght: ZIO[Console, IOException, Int] = getStrLn.map(_.length)
// flatMap takes another ZIO
val saluteAndGetInputLength: ZIO[Console, IOException, Int] =
putStrLn("Hello, what's your name?").flatMap(_ => inputLenght)
// either will take a ZIO[R, E, A] into a ZIO[R, Nothing, Either[E, A]]
getStrLn.either.flatMap {
case Right(name) => putStrLn(s"Hello $name")
case Left(e) => putStrLn(s"An exception arose: ${e.getCause}")
}
// absolve is the opposite of either, taking
// ZIO[R, Nothing, Either[E, A]] into ZIO[R, E, A]
// We could alternatively use fold
getStrLn.fold(
e => putStrLn(s"An exception arose: ${e.getCause}"),
name => putStrLn(s"Hello $name")
)
// orDie will ignore the Error, it's not very recommended
val getInput: URIO[Console, String] = getStrLn.orDie
// Use zip to combine two ZIOs
getStrLn.zip(getStrLn): ZIO[Console, IOException, (String, String)]
// Collect from many ZIOs
val getNumbers: Seq[ZIO[Console, IOException, String]] =
(1 to 10).toSeq.map(_ => getStrLn)
val favoriteNumbers: ZIO[Console, IOException, Seq[String]] =
putStrLn("Tell us your 10 favorite numbers").flatMap { _ =>
ZIO.collectAllPar(getNumbers)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment