Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:26
Show Gist options
  • Select an option

  • Save dacr/306afe2f0dd83b4ff1cd75630b3ce91b to your computer and use it in GitHub Desktop.

Select an option

Save dacr/306afe2f0dd83b4ff1cd75630b3ce91b to your computer and use it in GitHub Desktop.
ZIO learning - using cached with renew automatically the underlying effect ? / published by https://github.com/dacr/code-examples-manager #17b65c6e-4664-41a0-b01b-f71a98889e64/5659e9e4c6820a4557ce906e5f7fbc6e31eae576
// summary : ZIO learning - using cached with renew automatically the underlying effect ?
// 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 : 17b65c6e-4664-41a0-b01b-f71a98889e64
// created-on : 2022-01-26T18:19:59+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(): ZIO[Any, Option[Throwable], AuthToken] = {
ZIO
.attempt(AuthToken(java.util.UUID.randomUUID().toString))
.timeout(3.seconds)
.retry(Schedule.exponential(50.millis, 2).jittered && Schedule.recurs(4))
.some
}
}
val run = for {
ref <- AuthToken().flatMap(Ref.make)
getTokenAndRenew = AuthToken().flatMap(newToken => ref.modify(n => (n, newToken)))
cachedInvalidator <- getTokenAndRenew.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