Slide 1

Slide 1 text

ZIO from Home Wiem Zine Elabidine @WiemZin Stay Safe

Slide 2

Slide 2 text

Functional Effects

Slide 3

Slide 3 text

Functional Programming Pure functions Referential transparency. Composability Combine functions together to build new data. Immutability Values couldn’t be changed. Data & Functionality Pass data through functions to change its behaviors.

Slide 4

Slide 4 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic

Slide 5

Slide 5 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic def toInt(str: String): Try[Int] = Try(str.toInt)

Slide 6

Slide 6 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic def toInt(str: String): Try[Int] = Try(str.toInt) toInt("One")

Slide 7

Slide 7 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic def toInt(str: String): Try[Int] = Try(str.toInt) toInt("One") Failure(java.lang.NumberFormatException: For input string: "One")

Slide 8

Slide 8 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic def nextDay(day: DayOfWeek): String = day.plus(1) .toString assert(nextDay(THURSDAY)))(equalTo("FRIDAY"))

Slide 9

Slide 9 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic def nextDay(day: DayOfWeek): String = day.plus(1) .toString assert(nextDay(THURSDAY)))(equalTo("FRIDAY"))

Slide 10

Slide 10 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic def add(pasta: Pasta, sauce: Sauce, water: Water): Cooked[Pasta] = { val p = water.boil.map(_.put(pasta)) p.addSauce(sauce) }

Slide 11

Slide 11 text

Stay home safe and use what you have No Side effects Pure Function Trust your types Total Test your functions Deterministic

Slide 12

Slide 12 text

Effects are useful ❏ handle events ❏ Send messages ❏ read from the DataBase ❏ persist information ❏ print out the result ❏ retry in event of errors ❏ send result to other services ❏ ... Real World Applications

Slide 13

Slide 13 text

Abstract your programs! Describe everything in immutable data type! Functional Effects Effects as values?

Slide 14

Slide 14 text

Functional Effects case class IO[A](unsafeRun: () => A) { def map[B](f: A => B): IO[B] = ??? def flatMap[B](f: A => IO[B]): IO[B] = ??? } object IO { def effect[A](a: => A): IO[A] = new IO[A](() => a) }

Slide 15

Slide 15 text

Functional Program val program: IO[Unit] = for { event <- IO.effect(handleEvent) user <- IO.effect(getUser(event.userId)) _ <- IO.effect(logInfo(user)) ... } yield ()

Slide 16

Slide 16 text

Functional Program val program: IO[Unit] = for { event <- IO.effect(handleEvent) user <- IO.effect(getUser(event.userId)) _ <- IO.effect(logInfo(user)) ... } yield () program.unsafeRun()

Slide 17

Slide 17 text

Execution Just do it! Description Make a plan A - Z Be prepared!

Slide 18

Slide 18 text

● Control over all type of interactions ● Testability ● Refactoring Why Functional Effects?

Slide 19

Slide 19 text

Functional Effects case class IO[A](unsafeRun: () => A) { def map[B](f: A => B): IO[B] = ??? def flatMap[B](f: A => IO[B]): IO[B] = ??? } object IO { def effect[A](a: => A): IO[A] = new IO[A](() => a) }

Slide 20

Slide 20 text

ZIO Zero dependency Scala library for asynchronous and concurrent programming using purely functional code.

Slide 21

Slide 21 text

Functional Effects in ZIO ZIO[R, E, A] Description of a program R E A Dependencies Error Success

Slide 22

Slide 22 text

Functional Effects in ZIO RIO[R, A] Description of a program R Throwable A Dependencies Error Success

Slide 23

Slide 23 text

Functional Effects in ZIO URIO[R, A] Description of a program R A Dependencies Success

Slide 24

Slide 24 text

Functional Effects in ZIO Task[A] Description of a program Throwable A Error Success

Slide 25

Slide 25 text

Functional Effects in ZIO IO[E, A] Description of a program E A Error Success

Slide 26

Slide 26 text

Functional Effects in ZIO UIO[A] Description of a program A Success

Slide 27

Slide 27 text

Run Effects object Main extends zio.App { override def run(args: List[String]): IO[Nothing, Int] = program.fold(_ => 1, _ => 0) } OR object Main { Runtime.default.unsafeRun(program) }

Slide 28

Slide 28 text

Error Management

Slide 29

Slide 29 text

Error Management Throwable def divideM(a: Int, b: Int): Task[Int] = Task(divide(a, b)) Task[Int] Throwable Int

Slide 30

Slide 30 text

Error Management Throwable val throwException: Task[Nothing] = Task(throw new Exception("sorry")) Task[Nothing] Throwable

Slide 31

Slide 31 text

Error Management String val failedIO: IO[String, Nothing] = IO.fail("sorry again") IO[String, Nothing] String

Slide 32

Slide 32 text

Error Management Customized Errors sealed trait Error object Error { case class UserNotFound(id: UserId) extends Error case class InternalServer(t: Throwable) extends Error ... } val program: IO[Error, Unit] = ???

Slide 33

Slide 33 text

Error Management Customized Errors val program: IO[Error, Unit] = for { userId <- requestListener // IO[InternalServer, UserId] user <- getUser(userId) // IO[UserNotFound, User] _ <- logInfo(user) // IO[ Nothing, Unit] _ <- sendResponse(user) // IO[InternalServer, Unit] } yield ()

Slide 34

Slide 34 text

Error Management The state of the program val program: IO[Error, Unit] = ??? val programState: IO[Nothing, Exit[Error, Unit]] = program.run

Slide 35

Slide 35 text

Error Management Exit[E, A] Success[A] Failure[E]

Slide 36

Slide 36 text

Error Management Exit[E, A] Success[A] Failure[E]

Slide 37

Slide 37 text

Error Management Exit[E, A] Success[A] Failure[E] Cause[E]

Slide 38

Slide 38 text

Cause[E] Die Expected Error Unexpected Error, Exception Fail[E] Interrupted effect Interrupt

Slide 39

Slide 39 text

Many causes? Both(left, right) Both(Fail(e1), Then(Both(Fail(e2), Die(t)), Interrupt) Then(left, right)

Slide 40

Slide 40 text

Example: Cause.Both IO.fail("error1") .zipPar( IO.succeed(throw new Exception(" surprise!")) )

Slide 41

Slide 41 text

Example: Cause.Both IO.fail("error1") // Cause.Fail("error1") .zipPar( IO.succeed(throw new Exception(" surprise!")) )

Slide 42

Slide 42 text

Example: Cause.Both IO.fail("error1") // Cause.Fail("error1") .zipPar( IO.succeed(throw new Exception(" surprise!")) // Cause.Die(...) )

Slide 43

Slide 43 text

Example: Cause.Both IO.fail("error1") // Cause.Fail("error1") .zipPar( IO.succeed(throw new Exception(" surprise!")) // Cause.Die(...) ) ⇒ Both(Cause.Fail("error1"), Cause.Die(java.lang.Exception: surprise!)))

Slide 44

Slide 44 text

Example: Cause.Then IO.fail("error").ensuring(IO.die(new Exception("Don't try this at Home")))

Slide 45

Slide 45 text

Example: Cause.Then IO.fail("error").ensuring(IO.die(new Exception("Don't try this at Home"))) Fail("error")

Slide 46

Slide 46 text

Example: Cause.Then IO.fail("error").ensuring(IO.die(new Exception("Don't try this at Home"))) Fail("error") Die(java.lang.Exception Don’t try this at Home)

Slide 47

Slide 47 text

Example: Cause.Then IO.fail("error").ensuring(IO.die(new Exception("Don't try this at Home"))) Fail("error") Die(java.lang.Exception Don’t try this at Home) ⇒ Then(Cause.Fail("error"), Cause.Die(java.lang.Exception: Don’t try this at Home))

Slide 48

Slide 48 text

Error Management Expose all causes: def divide(a: Int, b: Int): IO[Cause[Throwable], Int] = Task(a / b).sandbox

Slide 49

Slide 49 text

Error Management Catch Errors: def divide(a: Int, b: Int): Task[Int] = Task(a / b) .catchSome{ case _: ArithmeticException => UIO(0) }

Slide 50

Slide 50 text

Error Management Peek at the errors: def divide(a: Int, b: Int): Task[Int] = Task(a / b) .tapError{ error => UIO(println(s"failed with: $e")) }

Slide 51

Slide 51 text

Error Management Fallback: val io1: IO[Error, Int] = ??? val io2: IO[String, Int] = ??? val result: IO[String, Int] = io1.orElse(io2)

Slide 52

Slide 52 text

Error Management Fallback: val loginUser: IO[Error, Profile] = ??? val loginAnonymous: IO[Throwable, LimitedProfile] = ??? val result: IO[Throwable, Either[Profile, LimitedProfile]] = loginUser.orElseEither(loginAnonymous)

Slide 53

Slide 53 text

Error Management Recover: def divide(a: Int, b: Int): UIO[Int] = Task(a / b).foldM(_ => UIO(0), n => UIO(n))

Slide 54

Slide 54 text

Error Management Crash it: def divide(a: Int, b: Int): UIO[Int] = Task(a / b).orDie

Slide 55

Slide 55 text

Error Management Make defects as expected errors: val io: IO[String, Nothing] = IO.succeed(throw new Exception("")) .unrefine(e => s"The error is: $e")

Slide 56

Slide 56 text

Error Management What about fatal Errors?

Slide 57

Slide 57 text

Error Management def simpleName[A](c: Class[A]) = c.getSimpleName object Example Task(simpleName(Example.getClass))

Slide 58

Slide 58 text

Error Management def simpleName[A](c: Class[A]) = c.getSimpleName object Example Task(simpleName(Example.getClass)) [error] java.lang.InternalError: Malformed class name [error] at java.lang.Class.getSimpleName(Class.java:1330)

Slide 59

Slide 59 text

Error Management object Main extends zio.App { override val platform: Platform = Platform.default.withFatal (_ => false) override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, Int] = { Task(simpleName(Example.getClass)).fold(_ =>1, _ => 0) } }

Slide 60

Slide 60 text

Error Management override val platform: Platform = new Platform { val executor = Executor.makeDefault(2) val tracing = Tracing.disabled def fatal(t: Throwable): Boolean = !t.isInstanceOf[InternalError] && t.isInstanceOf[VirtualMachineError] def reportFatal(t: Throwable): Nothing = { t.printStackTrace() throw t } def reportFailure(cause: Cause[Any]): Unit = { if (cause.died) System.err.println(cause.prettyPrint) } ... }

Slide 61

Slide 61 text

Build concurrent programs

Slide 62

Slide 62 text

ZIO Fibers Fibers are lightweight mechanism of concurrency. OS Thread ZIO Fiber Task1 Task2 Task3 ... ..

Slide 63

Slide 63 text

How ZIO runs Effects? ZIO[R, E, A]

Slide 64

Slide 64 text

How ZIO runs Effects? ZIO[R, E, A] R => IO[E, A]

Slide 65

Slide 65 text

How ZIO runs Effects? ZIO[R, E, A] R => IO[E, A]

Slide 66

Slide 66 text

How ZIO runs Effects? ZIO[R, E, A] R => IO[E, A]

Slide 67

Slide 67 text

How ZIO runs Effects? IO[E, A]

Slide 68

Slide 68 text

How ZIO runs Effects? IO[E, A] Fiber[E, A] unsafeRun

Slide 69

Slide 69 text

How ZIO runs Effects? IO[E, A] Fiber[E, A] unsafeRun

Slide 70

Slide 70 text

How ZIO runs Effects? IO[E, A] Fiber[E, A] unsafeRun

Slide 71

Slide 71 text

How ZIO runs concurrent Effects? IO[E, A] Fiber[E, A] unsafeRun IO[Nothing,Fiber[E, A]] fork

Slide 72

Slide 72 text

How ZIO runs concurrent Effects? IO[E, A] Fiber[E, A] unsafeRun IO[Nothing,Fiber[E, A]] fork

Slide 73

Slide 73 text

How ZIO runs concurrent Effects? IO[E, A] Fiber[E, A] unsafeRun IO[Nothing,Fiber[E, A]] fork Fiber[E, A] unsafeRun

Slide 74

Slide 74 text

How ZIO runs concurrent Effects? IO[E, A] Fiber[E, A] unsafeRun IO[Nothing,Fiber[E, A]] fork Fiber[E, A] unsafeRun

Slide 75

Slide 75 text

Concurrent Tasks trait ZIO[R, E, A] { def race(that: ZIO[R, E, A]): ZIO[R, E, A] def raceAll(ios: Iterable[ZIO[R, E, A]]): ZIO[R, E, A] def zipPar(that: ZIO[R, E, B]): ZIO[R, E, (A, B)] def on(ec: ExecutionContext): ZIO[R, E, A] ... } object ZIO { def foreachPar(as: Iterable[A])(fn: A => ZIO[R, E, B]): ZIO[R, E, List[B]] ... }

Slide 76

Slide 76 text

Concurrent Tasks def getUserInfo(id: Id): Task[(User, Profile)] = fetchUser(id).zipPar(fetchProfile(id)) Task 1 Task 2 (User, Profile)

Slide 77

Slide 77 text

Example case class IlForno(queue: Queue[Request], currentIngredients: Ref[Ingredients]) { def handleRequests(p: Promise[Nothing, Unit]): ZIO[Clock, MissingIngredient, Unit] = (for { request <- queue.take rest <- currentIngredients.update(preparePizza(request, _)) _ <- evaluate(rest) } yield ()) .tapError(_ => p.succeed(())) .repeat(Schedule.duration(8.hours) && Schedule.spaced(10.minutes)) .unit val listenRequests: IO[Error, Unit] = ??? }

Slide 78

Slide 78 text

val program: ZIO[Clock, Error, Unit] = for { ilForno <- IlForno(initialIngredient) f1 <- ilForno.listenRequests.fork p <- Promise.make[Nothing, Unit] f2 <- ilForno.handleRequests(p).fork _ <- p.await _ <- f1.interrupt.zipPar(f2.interrupt) } yield () Example

Slide 79

Slide 79 text

Example val program: ZIO[Clock, Error, Unit] = for { ilForno <- IlForno(initialIngredient) f1 <- ilForno.listenRequests.fork p <- Promise.make[Nothing, Unit] f2 <- ilForno.handleRequests(p).fork _ <- p.await _ <- f1.interrupt.zipPar(f2.interrupt) } yield ()

Slide 80

Slide 80 text

Example val program: ZIO[Clock, Error, Unit] = for { ilForno <- IlForno(initialIngredient) f1 <- ilForno.listenRequests.fork p <- Promise.make[Nothing, Unit] f2 <- ilForno.handleRequests(p).fork _ <- p.await _ <- f1.interrupt.zipPar(f2.interrupt) } yield ()

Slide 81

Slide 81 text

Example val program: ZIO[Clock, Error, Unit] = for { ilForno <- IlForno(initialIngredient) f1 <- ilForno.listenRequests.fork p <- Promise.make[Nothing, Unit] f2 <- ilForno.handleRequests(p).fork _ <- p.await _ <- f1.interrupt.zipPar(f2.interrupt) } yield ()

Slide 82

Slide 82 text

Resource Management

Slide 83

Slide 83 text

Resource Management File Connection Open / close / use = Acquire / release / use Database Clients

Slide 84

Slide 84 text

Resource Management IO.effect(startApp) .ensuring( console.putStr("Shutdown ...")) ensuring 01

Slide 85

Slide 85 text

Resource Management IO.effect(startApp) .ensuring( console.putStr("Shutdown ...")) createClient(config) .bracket(_.close)(c => processEvents(c)) ensuring bracket 01 02

Slide 86

Slide 86 text

Resource Management IO.effect(startApp) .ensuring( console.putStr("Shutdown ...")) ensuring val resource = Managed.make(openFile(file))(_.close) ... resource.use(computeLines) Management bracket 01 03 02 createClient(config) .bracket(_.close)(c => processEvents(c))

Slide 87

Slide 87 text

Resource Management ● You can use the methods provided by the dependencies in your program. ● once you provide a layer or an environment, the implementation will be acquired and used then released at the end. ZIO Environment & ZLayer[R, E, A]

Slide 88

Slide 88 text

ZIO is Awesome

Slide 89

Slide 89 text

WrapUp documentation https://github.com/zio/zio zio.dev ZIO projects Blog post https://medium.com/@wiemzin

Slide 90

Slide 90 text

CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon, and infographics & images by Freepik THANKS Follow me: @WiemZin Please keep this slide for attribution