Search code examples
scalalazy-evaluationscalazio-monadzio

How do I make a Scalaz ZIO lazy?


I have a heavy side-effecting function (think database call) that I want to use as a lazy value, so that it gets called only on first use (and not at all if never used).

How do I do this with ZIO?

If my program looks like this, the function gets called only once (but even the result is not used at all):

import scalaz.zio.IO
import scalaz.zio.console._

object Main extends scalaz.zio.App {

  def longRunningDbAction: IO[Nothing, Integer] = for {
    _ <- putStrLn("Calling the database now")
  } yield 42

  def maybeUseTheValue(x: Integer): IO[Nothing, Unit] = for {
    _ <- putStrLn(s"The database said ${x}")
  } yield ()

  def maybeNeedItAgain(x: Integer): IO[Nothing, Unit] = for {
    _ <- putStrLn("Okay, we did not need it again here.")
  } yield ()

 override def run(args: List[String]): IO[Nothing, Main.ExitStatus] = for {
    valueFromDb <- longRunningDbAction
    _ <- maybeUseTheValue(valueFromDb)
    _ <- maybeNeedItAgain(valueFromDb)
  } yield ExitStatus.ExitNow(0)

}

I suppose I have to pass an IO that produces the Int instead of the already materialized Int, but if I pass in the original IO that just calls the database, it will be called repeatedly:

object Main extends scalaz.zio.App {

  def longRunningDbAction: IO[Nothing, Integer] = for {
    _ <- putStrLn("Calling the database now")
  } yield 42


  def maybeUseTheValue(x: IO[Nothing, Integer]): IO[Nothing, Unit] = for {
    gettingItNow <- x
    _ <- putStrLn(s"The database said ${gettingItNow}")
  } yield ()

  def maybeNeedItAgain(x: IO[Nothing, Integer]): IO[Nothing, Unit] = for {
    gettingItNow <- x
    _ <- putStrLn(s"Okay, we need it again here: ${gettingItNow}")
  } yield ()

  override def run(args: List[String]): IO[Nothing, Main.ExitStatus] = for {
    _ <- maybeUseTheValue(longRunningDbAction)
    _ <- maybeNeedItAgain(longRunningDbAction)
  } yield ExitStatus.ExitNow(0)

}

Is there a way to "wrap" the longRunningDbAction into something that makes it lazy?


Solution

  • ZIO has memoize now.

    override def run(args: List[String]): IO[Nothing, Main.ExitStatus] = for {
       valueFromDb <- ZIO.memoize(longRunningDbAction)
       _ <- maybeUseTheValue(valueFromDb)
       _ <- maybeNeedItAgain(valueFromDb)
    } yield ExitStatus.ExitNow(0)
    

    It does essentially the same thing as this answer: Source looks like this

    /**
       * Returns an effect that, if evaluated, will return the lazily computed result
       * of this effect.
       */
      final def memoize: ZIO[R, Nothing, IO[E, A]] =
        for {
          r <- ZIO.environment[R]
          p <- Promise.make[E, A]
          l <- Promise.make[Nothing, Unit]
          _ <- (l.await *> ((self provide r) to p)).fork
        } yield l.succeed(()) *> p.await