Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/d7a4e856c19a2731d3f6f59f88ba968c to your computer and use it in GitHub Desktop.
Save dacr/d7a4e856c19a2731d3f6f59f88ba968c to your computer and use it in GitHub Desktop.
ZIO learning - using cached with renew automatically / published by https://github.com/dacr/code-examples-manager #85442628-9054-4125-8aab-93057e8ef275/c89ca15e284acd7e03776b414d9086b9d7b5d151
// summary : ZIO learning - using cached with renew automatically
// keywords : scala, cached, ttl, zio, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 85442628-9054-4125-8aab-93057e8ef275
// created-on : 2022-01-26T17:58:13+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
// ---------------------
import zio.*
object Encapsulated extends ZIOAppDefault {
case class AuthToken(token: String) {
override def toString: String = token
}
object AuthToken {
def apply(): AuthToken = AuthToken(java.util.UUID.randomUUID().toString)
}
val run = for {
ref <- Ref.make(AuthToken())
getAndRenew = ref.modify(n => (n, AuthToken()))
cachedInvalidator <- getAndRenew.cachedInvalidate(2.seconds)
(cached, invalidator) = cachedInvalidator
a1 <- cached
a2 <- cached
_ <- invalidator // Enough to invalidate !
a3 <- cached
a4 <- cached
_ <- Clock.sleep(2100.millis)
a5 <- cached
a6 <- cached
_ <- Console.printLine(List(a1, a2, a3, a4, a5, a6).mkString("\n"))
} yield ()
}
Encapsulated.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment