How to run effects in Zio

zio
Reading Time: 3 minutes

As we all know ZIO is a zero-dependency library for asynchronous and concurrent programming in Scala. It is a functional effect system in Scala. A functional effect is a description of doing some operations(“println(“Hello World”) in a pure functional way(“zio.console.putStrLn(“Hello World”)”.

In Zio we create the programs using the different ZIO constructors and combinators.

These programs are basically the ZIO effects which are just a data structure that describes the execution of a concurrent program.

In this blog we disscuss how can we execute these ZIO effects using the Runtime[R].

Library Dependency

Add the given dependency to your build.sbt file:

libraryDependencies += "dev.zio" %% "zio" % "1.0.12"

Runtime System

Runtime[R] is capable of executing tasks within an environment R.When we write code for ZIO program in actual way we are describing its structure so we need to run these program.

The ZIO Runtime System is responsible for execution of all the instructions of a ZIO program.

Its takes both the ZIO effect (ZIO[R, E, A]) and its environment (R) and will run this effect and then will return its result as an Either[E, A] value.

It is the responsibility of Runtime to execute every step of structure,hadle errors,provide concurrency and handle asynchronous callback.

Running a ZIO Effect

When we’re developing a ZIO application, we are composing ZIO values together to create the whole application logic, finally we have a single ZIO value that we need to run using ZIO Runtime.

There are two ways of running a zio effect:-

  1. By using the zio.App trait
  2. By using the unsafeRun method.

Using zio.App

This is the most commonly used way of running a zio effect.This way override the run method of trait App of zio library in other thee run method is the entry point of our application. 

The ZIO Runtime will call that function to execute our application.

package zio
trait App {
  def run(args: List[String]): URIO[ZEnv, ExitCode]
}

Lets see a example of running a effect using zio.App.

import zio.console._
object MyZioApp extends zio.App {
  
  val result: ZIO[Console, IOException, Unit] =
    for {
      _ <- putStrLn("Welcome to zio World")
    } yield ()
  override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
    result.exitCode
}

In the above example, the type of result is ZIO[Console, IOException, Unit]. The environment of this effect is Console.

It means that the ZIO Runtime needs the Console service to run this effect. The E type parameter is IOException, and the A parameter is Unit. This means that running this effect returns the Unit value or may throw IOException.

By override the run method of trait App we run the result effect as show in the example.

Using unsafeRun

This is the second way of execute of zio effect using the unsafeRun method provided by Runtime System of zio.

 final def unsafeRun[E, A](zio: => ZIO[R, E, A]): A =
    unsafeRunSync(zio).getOrElse(c => throw FiberFailure(c))

This method executes the effect synchronously, failing with [[zio.FiberFailure]] if there are any errors.


import zio.console._

object MyZioAppUsingUnsafeRun extends scala.App {
  
  val result: ZIO[Console, IOException, Unit] =
    for {
      _ <- putStrLn("Welcome to zio World")
    } yield ()

  zio.Runtime.default.unsafeRun(
    result
  )
}

In this example we use the zio default Runtime which provide the different ZIO modules (ConsoleSystemClockRandomScheduler, and on the JVM, Blocking) as it helps in execution of tasks.

We can also create our custom Runtime as our requirement for running the effects.This method is mainly used for refactor the non effectful code to ZIO effect.

Conclusion

In this we learn how to run effect using the two different ways.However it is the responsibility of Runtime System to successfully execute all the ZIO effect and handle errors.

In other words it is up to us which way we are used for running the zio effect as different situation need different way.

References

Zio documentation https://zio.dev/

Written by 

Akash Kumar is a Software Consultant at Knoldus Software LLP. He has done B.tech from Abdul Kalam Technical University. He is majorly focused on Scala and Angular. On the personnel side, he loves to play Cricket and online video games.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading