Last active
February 3, 2026 20:20
-
-
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/58f4d34eb0047a4ff0d034503a721ea9b918e6be
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // summary : ZIO learning - using cached with renew automatically | |
| // keywords : scala, cached, ttl, zio, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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.4.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