如何使Scalaz ZIO变得懒惰? [英] 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).
我该如何使用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)
}
我想我必须传递一个生成Int
的IO
,而不是已经实现的Int
,但是如果我传递只调用数据库的原始IO
,它将被重复调用:
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)
}
是否有一种方法可以将longRunningDbAction
包装成使其变得懒惰的东西?
Is there a way to "wrap" the longRunningDbAction
into something that makes it lazy?
推荐答案
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
这篇关于如何使Scalaz ZIO变得懒惰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!