Skip to main content
Version: ZIO 2.x

ZIO

A ZIO[R, E, A] value is an immutable value that lazily describes a workflow or job. The workflow requires some environment R, and may fail with an error of type E, or succeed with a value of type A.

A value of type ZIO[R, E, A] is like an effectful version of the following function type:

R => Either[E, A]

This function, which requires an R, might produce either an E, representing failure, or an A, representing success. ZIO effects are not actually functions, of course, because they model complex effects, like asynchronous and concurrent effects.

ZIO effects model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction.

ZIO effects use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability.

The ZIO[R, E, A] data type has three type parameters:

  • R - Environment Type. The effect requires an environment of type R. If this type parameter is Any, it means the effect has no requirements, because we can run the effect with any value (for example, the unit value ()).
  • E - Failure Type. The effect may fail with a value of type E. Some applications will use Throwable. If this type parameter is Nothing, it means the effect cannot fail, because there are no values of type Nothing.
  • A - Success Type. The effect may succeed with a value of type A. If this type parameter is Unit, it means the effect produces no useful information, while if it is Nothing, it means the effect runs forever (or until failure).

In the following example, the readLine function requires the Console service, it may fail with value of type IOException, or may succeed with a value of type String:

val readLine: ZIO[Has[Console], IOException, String] =  ZIO.serviceWith(_.readLine)

ZIO values are immutable, and all ZIO functions produce new ZIO values, enabling ZIO to be reasoned about and used like any ordinary Scala immutable data structure.

ZIO values do not actually do anything; they are just values that model or describe effectful interactions.

ZIO can be interpreted by the ZIO runtime system into effectful interactions with the external world. Ideally, this occurs at a single time, in our application's main function. The App class provides this functionality automatically.

Creation#

In this section we explore some of the common ways to create ZIO effects from values, from common Scala types, and from both synchronous and asynchronous side-effects. Here is the summary list of them:

Success Values#

FunctionInput TypeOutput Type
succeedAUIO[A]

Using the ZIO.succeed method, we can create an effect that succeeds with the specified value:

val s1 = ZIO.succeed(42)

We can also use methods in the companion objects of the ZIO type aliases:

val s2: Task[Int] = Task.succeed(42)

Failure Values#

FunctionInput TypeOutput Type
failEIO[E, Nothing]

Using the ZIO.fail method, we can create an effect that models failure:

val f1 = ZIO.fail("Uh oh!")

For the ZIO data type, there is no restriction on the error type. We may use strings, exceptions, or custom data types appropriate for our application.

Many applications will model failures with classes that extend Throwable or Exception:

val f2 = Task.fail(new Exception("Uh oh!"))

Note that unlike the other effect companion objects, the UIO companion object does not have UIO.fail, because UIO values cannot fail.

From Values#

ZIO contains several constructors which help us to convert various data types into the ZIO effect.

Option#

FunctionInput TypeOutput Type
fromOptionOption[A]IO[Option[Nothing], A]
someAUIO[Option[A]]
noneUIO[Option[Nothing]]
getOrFailOption[A]Task[A]
getOrFailUnitOption[A]IO[Unit, A]
getOrFailWithe:=> E, v:=> Option[A]IO[E, A]

An Option can be converted into a ZIO effect using ZIO.fromOption:

val zoption: IO[Option[Nothing], Int] = ZIO.fromOption(Some(2))

The error type of the resulting effect is Option[Nothing], which provides no information on why the value is not there. We can change the Option[Nothing] into a more specific error type using ZIO#mapError:

val zoption2: IO[String, Int] = zoption.mapError(_ => "It wasn't there!")

We can also readily compose it with other operators while preserving the optional nature of the result (similar to an OptionT)

val maybeId: IO[Option[Nothing], String] = ZIO.fromOption(Some("abc123"))def getUser(userId: String): IO[Throwable, Option[User]] = ???def getTeam(teamId: String): IO[Throwable, Team] = ???

val result: IO[Throwable, Option[(User, Team)]] = (for {  id   <- maybeId  user <- getUser(id).some  team <- getTeam(user.teamId).asSomeError } yield (user, team)).unsome 

Either#

FunctionInput TypeOutput Type
fromEitherEither[E, A]IO[E, A]
leftAUIO[Either[A, Nothing]]
rightAUIO[Either[Nothing, B]]

An Either can be converted into a ZIO effect using ZIO.fromEither:

val zeither = ZIO.fromEither(Right("Success!"))

The error type of the resulting effect will be whatever type the Left case has, while the success type will be whatever type the Right case has.

Try#

FunctionInput TypeOutput Type
fromTryscala.util.Try[A]Task[A]

A Try value can be converted into a ZIO effect using ZIO.fromTry:

import scala.util.Try
val ztry = ZIO.fromTry(Try(42 / 0))

The error type of the resulting effect will always be Throwable, because Try can only fail with values of type Throwable.

Future#

FunctionInput TypeOutput Type
fromFutureExecutionContext => scala.concurrent.Future[A]Task[A]
fromFutureJavajava.util.concurrent.Future[A]RIO[Blocking, A]
fromFunctionFutureR => scala.concurrent.Future[A]RIO[R, A]
fromFutureInterruptExecutionContext => scala.concurrent.Future[A]Task[A]

A Future can be converted into a ZIO effect using ZIO.fromFuture:

import scala.concurrent.Future
lazy val future = Future.successful("Hello!")
val zfuture: Task[String] =  ZIO.fromFuture { implicit ec =>    future.map(_ => "Goodbye!")  }

The function passed to fromFuture is passed an ExecutionContext, which allows ZIO to manage where the Future runs (of course, we can ignore this ExecutionContext).

The error type of the resulting effect will always be Throwable, because Future can only fail with values of type Throwable.

Promise#

FunctionInput TypeOutput Type
fromPromiseScalascala.concurrent.Promise[A]Task[A]

A Promise can be converted into a ZIO effect using ZIO.fromPromiseScala:

val func: String => String = s => s.toUpperCasefor {  promise <- ZIO.succeed(scala.concurrent.Promise[String]())  _ <- ZIO.attempt {    Try(func("hello world from future")) match {      case Success(value) => promise.success(value)      case Failure(exception) => promise.failure(exception)    }  }.fork  value <- ZIO.fromPromiseScala(promise)  _ <- Console.printLine(s"Hello World in UpperCase: $value")} yield ()

Fiber#

FunctionInput TypeOutput Type
fromFiberFiber[E, A]IO[E, A]
fromFiberZIOIO[E, Fiber[E, A]]IO[E, A]

A Fiber can be converted into a ZIO effect using ZIO.fromFiber:

val io: IO[Nothing, String] = ZIO.fromFiber(Fiber.succeed("Hello From Fiber!"))

From Side-Effects#

ZIO can convert both synchronous and asynchronous side-effects into ZIO effects (pure values).

These functions can be used to wrap procedural code, allowing us to seamlessly use all features of ZIO with legacy Scala and Java code, as well as third-party libraries.

Synchronous#

FunctionInput TypeOutput TypeNote
succeedAUIO[A]Imports a total synchronous effect
attemptATask[A]Imports a (partial) synchronous side-effect

A synchronous side-effect can be converted into a ZIO effect using ZIO.attempt:

import scala.io.StdIn
val getLine: Task[String] =  ZIO.attempt(StdIn.readLine())

The error type of the resulting effect will always be Throwable, because side-effects may throw exceptions with any value of type Throwable.

If a given side-effect is known to not throw any exceptions, then the side-effect can be converted into a ZIO effect using ZIO.succeed:

def printLine(line: String): UIO[Unit] =  ZIO.succeed(println(line))
val succeedTask: UIO[Long] =  ZIO.succeed(java.lang.System.nanoTime())

We should be careful when using ZIO.succeed—when in doubt about whether or not a side-effect is total, prefer ZIO.attempt to convert the effect.

If this is too broad, the refineOrDie method of ZIO may be used to retain only certain types of exceptions, and to die on any other types of exceptions:

import java.io.IOException
val printLine2: IO[IOException, String] =  ZIO.attempt(StdIn.readLine()).refineToOrDie[IOException]
Blocking Synchronous Side-Effects#
FunctionInput TypeOutput Type
blockingZIO[R, E, A]ZIO[R, E, A]
attemptBlockingARIO[Blocking, A]
attemptBlockingCancelableeffect: => A, cancel: UIO[Unit]RIO[Blocking, A]
attemptBlockingInterruptARIO[Blocking, A]
attemptBlockingIOAZIO[Blocking, IOException, A]

Some side-effects use blocking IO or otherwise put a thread into a waiting state. If not carefully managed, these side-effects can deplete threads from our application's main thread pool, resulting in work starvation.

ZIO provides the zio.blocking package, which can be used to safely convert such blocking side-effects into ZIO effects.

A blocking side-effect can be converted directly into a ZIO effect blocking with the attemptBlocking method:


val sleeping =  ZIO.attemptBlocking(Thread.sleep(Long.MaxValue))

The resulting effect will be executed on a separate thread pool designed specifically for blocking effects.

Blocking side-effects can be interrupted by invoking Thread.interrupt using the attemptBlockingInterrupt method.

Some blocking side-effects can only be interrupted by invoking a cancellation effect. We can convert these side-effects using the attemptBlockingCancelable method:

import java.net.ServerSocketimport zio.UIO
def accept(l: ServerSocket) =  ZIO.attemptBlockingCancelable(l.accept())(UIO.succeed(l.close()))

If a side-effect has already been converted into a ZIO effect, then instead of attemptBlocking, the blocking method can be used to ensure the effect will be executed on the blocking thread pool:

import scala.io.{ Codec, Source }
def download(url: String) =  Task.attempt {    Source.fromURL(url)(Codec.UTF8).mkString  }
def safeDownload(url: String) =  ZIO.blocking(download(url))

Asynchronous#

FunctionInput TypeOutput Type
async(ZIO[R, E, A] => Unit) => AnyZIO[R, E, A]
asyncZIO(ZIO[R, E, A] => Unit) => ZIO[R, E, Any]ZIO[R, E, A]
asyncMaybe(ZIO[R, E, A] => Unit) => Option[ZIO[R, E, A]]ZIO[R, E, A]
asyncInterrupt(ZIO[R, E, A] => Unit) => Either[Canceler[R], ZIO[R, E, A]]ZIO[R, E, A]

An asynchronous side-effect with a callback-based API can be converted into a ZIO effect using ZIO.async:

object legacy {  def login(    onSuccess: User => Unit,    onFailure: AuthError => Unit): Unit = ???}
val login: IO[AuthError, User] =  IO.async[AuthError, User] { callback =>    legacy.login(      user => callback(IO.succeed(user)),      err  => callback(IO.fail(err))    )  }

Asynchronous ZIO effects are much easier to use than callback-based APIs, and they benefit from ZIO features like interruption, resource-safety, and superior error handling.

Creating Suspended Effects#

FunctionInput TypeOutput Type
suspendRIO[R, A]RIO[R, A]
suspendSucceedZIO[R, E, A]ZIO[R, E, A]
suspendSucceedWith(RuntimeConfig, FiberId) => ZIO[R, E, A]ZIO[R, E, A]
suspendWith(RuntimeConfig, FiberId) => RIO[R, A]RIO[R, A]

A RIO[R, A] effect can be suspended using suspend function:

val suspendedEffect: RIO[Any, ZIO[Has[Console], IOException, Unit]] =  ZIO.suspend(ZIO.attempt(Console.printLine("Suspended Hello World!")))

Blocking Operations#

ZIO provides access to a thread pool that can be used for performing blocking operations, such as thread sleeps, synchronous socket/file reads, and so forth.

By default, ZIO is asynchronous and all effects will be executed on a default primary thread pool which is optimized for asynchronous operations. As ZIO uses a fiber-based concurrency model, if we run Blocking I/O or CPU Work workloads on a primary thread pool, they are going to monopolize all threads of primary thread pool.

In the following example, we create 20 blocking tasks to run parallel on the primary async thread pool. Assume we have a machine with an 8 CPU core, so the ZIO creates a thread pool of size 16 (2 * 8). If we run this program, all of our threads got stuck, and the remaining 4 blocking tasks (20 - 16) haven't any chance to run on our thread pool:

import zio._def blockingTask(n: Int): URIO[Has[Console], Unit] =  Console.printLine(s"running blocking task number $n").orDie *>    ZIO.succeed(Thread.sleep(3000)) *>    blockingTask(n)
val program = ZIO.foreachPar((1 to 100).toArray)(blockingTask)

Creating Blocking Effects#

ZIO has a separate blocking thread pool specially designed for Blocking I/O and, also CPU Work workloads. We should run blocking workloads on this thread pool to prevent interfering with the primary thread pool.

The contract is that the thread pool will accept unlimited tasks (up to the available memory) and continuously create new threads as necessary.

The blocking operator takes a ZIO effect and return another effect that is going to run on a blocking thread pool:

Also, we can directly import a synchronous effect that does blocking IO into ZIO effect by using attemptBlocking:

def blockingTask(n: Int) = ZIO.attemptBlocking {  do {    println(s"Running blocking task number $n on dedicated blocking thread pool")    Thread.sleep(3000)   } while (true)}

Interruption of Blocking Operations#

By default, when we convert a blocking operation into the ZIO effects using attemptBlocking, there is no guarantee that if that effect is interrupted the underlying effect will be interrupted.

Let's create a blocking effect from an endless loop:

for {  _ <- printLine("Starting a blocking operation")  fiber <- ZIO.attemptBlocking {    while (true) {      Thread.sleep(1000)      println("Doing some blocking operation")    }  }.ensuring(    Console.printLine("End of a blocking operation").orDie  ).fork  _ <- fiber.interrupt.schedule(    Schedule.delayed(      Schedule.duration(1.seconds)    )  )} yield ()

When we interrupt this loop after one second, it will not interrupted. It will only stop when the entire JVM stops. So the attemptBlocking doesn't translate the ZIO interruption into thread interruption (Thread.interrupt).

Instead, we should use attemptBlockingInterrupt to create interruptible blocking effects:

for {  _ <- printLine("Starting a blocking operation")  fiber <- ZIO.attemptBlockingInterrupt {    while(true) {      Thread.sleep(1000)      println("Doing some blocking operation")    }  }.ensuring(     Console.printLine("End of the blocking operation").orDie   ).fork  _ <- fiber.interrupt.schedule(    Schedule.delayed(      Schedule.duration(3.seconds)    )  )} yield ()

Notes:

  1. If we are converting a blocking I/O to the ZIO effect, it would be better to use attemptBlockingIO which refines the error type to the java.io.IOException.

  2. The attemptBlockingInterrupt method adds significant overhead. So for performance-sensitive applications, it is better to handle interruptions manually using attemptBlockingCancelable.

Cancellation of Blocking Operation#

Some blocking operations do not respect Thread#interrupt by swallowing InterruptedException. So, they will not be interrupted via attemptBlockingInterrupt. Instead, they may provide us an API to signal them to cancel their operation.

The following BlockingService will not be interrupted in case of Thread#interrupt call, but it checks the released flag constantly. If this flag becomes true, the blocking service will finish its job:

import java.util.concurrent.atomic.AtomicReferencefinal case class BlockingService() {  private val released = new AtomicReference(false)
  def start(): Unit = {    while (!released.get()) {      println("Doing some blocking operation")      try Thread.sleep(1000)      catch {        case _: InterruptedException => () // Swallowing InterruptedException      }    }    println("Blocking operation closed.")  }
  def close(): Unit = {    println("Releasing resources and ready to be closed.")    released.getAndSet(true)  }}

So, to translate ZIO interruption into cancellation of these types of blocking operations we should use attemptBlockingCancelable. This method takes a cancel effect which responsible to signal the blocking code to close itself when ZIO interruption occurs:

val myApp =  for {    service <- ZIO.attempt(BlockingService())    fiber   <- ZIO.attemptBlockingCancelable(      effect = service.start()    )(      cancel = UIO.succeed(service.close())    ).fork    _       <- fiber.interrupt.schedule(      Schedule.delayed(        Schedule.duration(3.seconds)      )    )  } yield ()

Here is another example of the cancelation of a blocking operation. When we accept a server socket, this blocking operation will never interrupted until we close that using ServerSocket#close method:

import java.net.{Socket, ServerSocket}def accept(ss: ServerSocket): Task[Socket] =  ZIO.attemptBlockingCancelable(ss.accept())(UIO.succeed(ss.close()))

Mapping#

map#

We can change an IO[E, A] to an IO[E, B] by calling the map method with a function A => B. This lets us transform values produced by actions into other values.

import zio.{ UIO, IO }
val mappedValue: UIO[Int] = IO.succeed(21).map(_ * 2)

mapError#

We can transform an IO[E, A] into an IO[E2, A] by calling the mapError method with a function E => E2. This lets us transform the failure values of effects:

val mappedError: IO[Exception, String] =   IO.fail("No no!").mapError(msg => new Exception(msg))

Note:

Note that mapping over an effect's success or error channel does not change the success or failure of the effect, in the same way that mapping over an Either does not change whether the Either is Left or Right.

mapEffect#

mapEffect returns an effect whose success is mapped by the specified side-effecting f function, translating any thrown exceptions into typed failed effects.

Converting literal "Five" String to Int by calling toInt is a side effecting because it will throws NumberFormatException exception:

val task: RIO[Any, Int] = ZIO.succeed("hello").mapAttempt(_.toInt)

mapEffect converts an unchecked exception to a checked one by returning the RIO effect.

Chaining#

We can execute two actions in sequence with the flatMap method. The second action may depend on the value produced by the first action.

val chainedActionsValue: UIO[List[Int]] = IO.succeed(List(1, 2, 3)).flatMap { list =>  IO.succeed(list.map(_ + 1))}

If the first effect fails, the callback passed to flatMap will never be invoked, and the composed effect returned by flatMap will also fail.

In any chain of effects, the first failure will short-circuit the whole chain, just like throwing an exception will prematurely exit a sequence of statements.

Because the ZIO data type supports both flatMap and map, we can use Scala's for comprehensions to build sequential effects:

val program =   for {    _    <- Console.printLine("Hello! What is your name?")    name <- Console.readLine    _    <- Console.printLine(s"Hello, ${name}, welcome to ZIO!")  } yield ()

For comprehensions provide a more procedural syntax for composing chains of effects.

Zipping#

We can combine two effects into a single effect with the zip method. The resulting effect succeeds with a tuple that contains the success values of both effects:

val zipped: UIO[(String, Int)] =   ZIO.succeed("4").zip(ZIO.succeed(2))

Note that zip operates sequentially: the effect on the left side is executed before the effect on the right side.

In any zip operation, if either the left or right-hand sides fail, then the composed effect will fail, because both values are required to construct the tuple.

zipLeft and zipRight#

Sometimes, when the success value of an effect is not useful (or example, it is Unit), it can be more convenient to use the zipLeft or zipRight functions, which first perform a zip, and then map over the tuple to discard one side or the other:

val zipRight1 =   Console.printLine("What is your name?").zipRight(readLine)

The zipRight and zipLeft functions have symbolic aliases, known as *> and <*, respectively. Some developers find these operators easier to read:

val zipRight2 =   Console.printLine("What is your name?") *>  Console.readLine

Parallelism#

ZIO provides many operations for performing effects in parallel. These methods are all named with a Par suffix that helps us identify opportunities to parallelize our code.

For example, the ordinary ZIO#zip method zips two effects together, sequentially. But there is also a ZIO#zipPar method, which zips two effects together in parallel.

The following table summarizes some of the sequential operations and their corresponding parallel versions:

DescriptionSequentialParallel
Zips two effects into oneZIO#zipZIO#zipPar
Zips two effects into oneZIO#zipWithZIO#zipWithPar
Collects from many effectsZIO.collectAllZIO.collectAllPar
Effectfully loop over valuesZIO.foreachZIO.foreachPar
Reduces many valuesZIO.reduceAllZIO.reduceAllPar
Merges many valuesZIO.mergeAllZIO.mergeAllPar

For all the parallel operations, if one effect fails, then others will be interrupted, to minimize unnecessary computation.

If the fail-fast behavior is not desired, potentially failing effects can be first converted into infallible effects using the ZIO#either or ZIO#option methods.

Racing#

ZIO lets us race multiple effects in parallel, returning the first successful result:

for {  winner <- IO.succeed("Hello").race(IO.succeed("Goodbye"))} yield winner

If we want the first success or failure, rather than the first success, then we can use left.either race right.either, for any effects left and right.

Timeout#

ZIO lets us timeout any effect using the ZIO#timeout method, which returns a new effect that succeeds with an Option. A value of None indicates the timeout elapsed before the effect completed.

IO.succeed("Hello").timeout(10.seconds)

If an effect times out, then instead of continuing to execute in the background, it will be interrupted so no resources will be wasted.

Error Management#

Either#

FunctionInput TypeOutput Type
ZIO#eitherURIO[R, Either[E, A]]
ZIO.absolveZIO[R, E, Either[E, A]]ZIO[R, E, A]

We can surface failures with ZIO#either, which takes an ZIO[R, E, A] and produces an ZIO[R, Nothing, Either[E, A]].

val zeither: UIO[Either[String, Int]] =   IO.fail("Uh oh!").either

We can submerge failures with ZIO.absolve, which is the opposite of either and turns an ZIO[R, Nothing, Either[E, A]] into a ZIO[R, E, A]:

def sqrt(io: UIO[Double]): IO[String, Double] =  ZIO.absolve(    io.map(value =>      if (value < 0.0) Left("Value must be >= 0.0")      else Right(Math.sqrt(value))    )  )

Catching#

FunctionInput TypeOutput Type
ZIO#catchAllE => ZIO[R1, E2, A1]ZIO[R1, E2, A1]
ZIO#catchAllCauseCause[E] => ZIO[R1, E2, A1]ZIO[R1, E2, A1]
ZIO#catchAllDefectThrowable => ZIO[R1, E1, A1]ZIO[R1, E1, A1]
ZIO#catchAllTrace((E, Option[ZTrace])) => ZIO[R1, E2, A1]ZIO[R1, E2, A1]
ZIO#catchSomePartialFunction[E, ZIO[R1, E1, A1]]ZIO[R1, E1, A1]
ZIO#catchSomeCausePartialFunction[Cause[E], ZIO[R1, E1, A1]]ZIO[R1, E1, A1]
ZIO#catchSomeDefectPartialFunction[Throwable, ZIO[R1, E1, A1]]ZIO[R1, E1, A1]
ZIO#catchSomeTracePartialFunction[(E, Option[ZTrace]), ZIO[R1, E1, A1]]ZIO[R1, E1, A1]

Catching All Errors#

If we want to catch and recover from all types of errors and effectfully attempt recovery, we can use the catchAll method:

val z: IO[IOException, Array[Byte]] =   readFile("primary.json").catchAll(_ =>     readFile("backup.json"))

In the callback passed to catchAll, we may return an effect with a different error type (or perhaps Nothing), which will be reflected in the type of effect returned by catchAll.

Catching Some Errors#

If we want to catch and recover from only some types of exceptions and effectfully attempt recovery, we can use the catchSome method:

val data: IO[IOException, Array[Byte]] =   readFile("primary.data").catchSome {    case _ : FileNotFoundException =>       readFile("backup.data")  }

Unlike catchAll, catchSome cannot reduce or eliminate the error type, although it can widen the error type to a broader class of errors.

Fallback#

FunctionInput TypeOutput Type
orElseZIO[R1, E2, A1]ZIO[R1, E2, A1]
orElseEitherZIO[R1, E2, B]ZIO[R1, E2, Either[A, B]]
orElseFailE1ZIO[R, E1, A]
orElseOptionalZIO[R1, Option[E1], A1]ZIO[R1, Option[E1], A1]
orElseSucceedA1URIO[R, A1]

We can try one effect, or, if it fails, try another effect, with the orElse combinator:

val primaryOrBackupData: IO[IOException, Array[Byte]] =   readFile("primary.data").orElse(readFile("backup.data"))

Folding#

FunctionInput TypeOutput Type
foldfailure: E => B, success: A => BURIO[R, B]
foldCausefailure: Cause[E] => B, success: A => BURIO[R, B]
foldZIOfailure: E => ZIO[R1, E2, B], success: A => ZIO[R1, E2, B]ZIO[R1, E2, B]
foldCauseZIOfailure: Cause[E] => ZIO[R1, E2, B], success: A => ZIO[R1, E2, B]ZIO[R1, E2, B]
foldTraceZIOfailure: ((E, Option[ZTrace])) => ZIO[R1, E2, B], success: A => ZIO[R1, E2, B]ZIO[R1, E2, B]

Scala's Option and Either data types have fold, which let us handle both failure and success at the same time. In a similar fashion, ZIO effects also have several methods that allow us to handle both failure and success.

The first fold method, fold, lets us non-effectfully handle both failure and success, by supplying a non-effectful handler for each case:

lazy val DefaultData: Array[Byte] = Array(0, 0)
val primaryOrDefaultData: UIO[Array[Byte]] =   readFile("primary.data").fold(    _    => DefaultData,    data => data)

The second fold method, foldZIO, lets us effectfully handle both failure and success, by supplying an effectful (but still pure) handler for each case:

val primaryOrSecondaryData: IO[IOException, Array[Byte]] =   readFile("primary.data").foldZIO(    _    => readFile("secondary.data"),    data => ZIO.succeed(data))

Nearly all error handling methods are defined in terms of foldZIO, because it is both powerful and fast.

In the following example, foldZIO is used to handle both failure and success of the readUrls method:

val urls: UIO[Content] =  readUrls("urls.json").foldZIO(    error   => IO.succeed(NoContent(error)),     success => fetchContent(success)  )

Retrying#

FunctionInput TypeOutput Type
retrySchedule[R1, E, S]ZIO[R1 with Has[Clock], E, A]
retryNn: IntZIO[R, E, A]
retryOrElsepolicy: Schedule[R1, E, S], orElse: (E, S) => ZIO[R1, E1, A1]ZIO[R1 with Has[Clock], E1, A1]
retryOrElseEitherschedule: Schedule[R1, E, Out], orElse: (E, Out) => ZIO[R1, E1, B]ZIO[R1 with Has[Clock], E1, Either[B, A]]
retryUntilE => BooleanZIO[R, E, A]
retryUntilEqualsE1ZIO[R, E1, A]
retryUntilZIOE => URIO[R1, Boolean]ZIO[R1, E, A]
retryWhileE => BooleanZIO[R, E, A]
retryWhileEqualsE1ZIO[R, E1, A]
retryWhileZIOE => URIO[R1, Boolean]ZIO[R1, E, A]

When we are building applications we want to be resilient in the face of a transient failure. This is where we need to retry to overcome these failures.

There are a number of useful methods on the ZIO data type for retrying failed effects.

The most basic of these is ZIO#retry, which takes a Schedule and returns a new effect that will retry the first effect if it fails, according to the specified policy:

val retriedOpenFile: ZIO[Has[Clock], IOException, Array[Byte]] =   readFile("primary.data").retry(Schedule.recurs(5))

The next most powerful function is ZIO#retryOrElse, which allows specification of a fallback to use, if the effect does not succeed with the specified policy:

readFile("primary.data").retryOrElse(  Schedule.recurs(5),   (_, _:Long) => ZIO.succeed(DefaultData))

The final method, ZIO#retryOrElseEither, allows returning a different type for the fallback.

Resource Management#

ZIO's resource management features work across synchronous, asynchronous, concurrent, and other effect types, and provide strong guarantees even in the presence of failure, interruption, or defects in the application.

Finalizing#

Scala has a try / finally construct which helps us to make sure we don't leak resources because no matter what happens in the try, the finally block will be executed. So we can open files in the try block, and then we can close them in the finally block, and that gives us the guarantee that we will not leak resources.

Asynchronous Try / Finally#

The problem with the try / finally construct is that it only applies with synchronous code, they don't work for asynchronous code. ZIO gives us a method called ensuring that works with either synchronous or asynchronous actions. So we have a functional try/finally but across the async region of our code, also our finalizer could have async regions.

Like try / finally, the ensuring operation guarantees that if an effect begins executing and then terminates (for whatever reason), then the finalizer will begin executing:

val finalizer =   UIO.succeed(println("Finalizing!"))// finalizer: UIO[Unit] = zio.ZIO$Succeed@2f55936d
val finalized: IO[String, Unit] =   IO.fail("Failed!").ensuring(finalizer)// finalized: IO[String, Unit] = zio.ZIO$Ensuring@7a68637f

The finalizer is not allowed to fail, which means that it must handle any errors internally.

Like try / finally, finalizers can be nested, and the failure of any inner finalizer will not affect outer finalizers. Nested finalizers will be executed in reverse order, and linearly (not in parallel).

Unlike try / finally, ensuring works across all types of effects, including asynchronous and concurrent effects.

Here is another example of ensuring that our clean-up action called before our effect is done:

import zio.Taskvar i: Int = 0val action: Task[String] =  Task.succeed(i += 1) *>    Task.fail(new Throwable("Boom!"))val cleanupAction: UIO[Unit] = UIO.succeed(i -= 1)val composite = action.ensuring(cleanupAction)

_Note: Finalizers offer very powerful guarantees, but they are low-level, and should generally not be used for releasing resources. For higher-level logic built on ensuring, see ZIO#acquireReleaseWith in the acquire release section.

Unstoppable Finalizers#

In Scala when we nest try / finally finalizers, they cannot be stopped. If we have nested finalizers and one of them fails for some sort of catastrophic reason the ones on the outside will still be run and in the correct order.

try {  try {    try {      ...    } finally f1  } finally f2} finally f3

Also in ZIO like try / finally, the finalizers are unstoppable. This means if we have a buggy finalizer, and it is going to leak some resources that unfortunately happens, we will leak the minimum amount of resources because all other finalizers will be run in the correct order.

val io = ???io.ensuring(f1) .ensuring(f2) .ensuring(f3)

AcquireRelease#

In Scala the try / finally is often used to manage resources. A common use for try / finally is safely acquiring and releasing resources, such as new socket connections or opened files:

val handle = openFile(name)
try {  processFile(handle)} finally closeFile(handle)

ZIO encapsulates this common pattern with ZIO#acquireRelease, which allows us to specify an acquire effect, which acquires a resource; a release effect, which releases it; and a use effect, which uses the resource. Acquire release lets us open a file and close the file and no matter what happens when we are using that resource.

The release action is guaranteed to be executed by the runtime system, even if the utilize action throws an exception or the executing fiber is interrupted.

Acquire release is a built-in primitive that let us safely acquire and release resources. It is used for a similar purpose as try/catch/finally, only acquire release work with synchronous and asynchronous actions, work seamlessly with fiber interruption, and is built on a different error model that ensures no errors are ever swallowed.

Acquire release consist of an acquire action, a utilize action (which uses the acquired resource), and a release action.

import zio.{ UIO, IO }
val groupedFileData: IO[IOException, Unit] = openFile("data.json").acquireReleaseWith(closeFile(_)) { file =>  for {    data    <- decodeData(file)    grouped <- groupData(data)  } yield grouped}

Acquire releases have compositional semantics, so if an acquire release is nested inside another acquire release, and the outer resource is acquired, then the outer release will always be called, even if, for example, the inner release fails.

Let's look at a full working example on using acquire release:

import zio._import java.io.{ File, FileInputStream }import java.nio.charset.StandardCharsets
object Main extends zio.App {
  // run my acquire release  def run(args: List[String]) =    myAcquireRelease.exitCode
  def closeStream(is: FileInputStream) =    UIO(is.close())
  // helper method to work around in Java 8  def readAll(fis: FileInputStream, len: Long): Array[Byte] = {    val content: Array[Byte] = Array.ofDim(len.toInt)    fis.read(content)    content  }
  def convertBytes(is: FileInputStream, len: Long) =    Task.attempt(println(new String(readAll(is, len), StandardCharsets.UTF_8))) // Java 8  //Task.attempt(println(new String(is.readAllBytes(), StandardCharsets.UTF_8))) // Java 11+
  // myAcquireRelease is just a value. Won't execute anything here until interpreted  val myAcquireRelease: Task[Unit] = for {    file   <- Task(new File("/tmp/hello"))    len    = file.length    string <- Task(new FileInputStream(file)).acquireReleaseWith(closeStream)(convertBytes(_, len))  } yield string}

Unswallowed Exceptions#

The Java and Scala error models are broken. Because if we have the right combinations of try/finally/catches we can actually throw many exceptions, and then we are only able to catch one of them. All the other ones are lost. They are swallowed into a black hole, and also the one that we catch is the wrong one. It is not the primary cause of the failure.

In the following example, we are going to show this behavior:

 try {    try throw new Error("e1")    finally throw new Error("e2") } catch {   case e: Error => println(e)  }

The above program just prints the e2, which is lossy and, also is not the primary cause of failure.

But in the ZIO version, all the errors will still be reported. So even though we are only able to catch one error, the other ones will be reported which we have full control over them. They don't get lost.

Let's write a ZIO version:

IO.fail("e1")  .ensuring(IO.succeed(throw new Exception("e2")))  .catchAll {    case "e1" => Console.printLine("e1")    case "e2" => Console.printLine("e2")  }