Skip to content

Instantly share code, notes, and snippets.

@samspills
Last active April 21, 2023 18:14
Show Gist options
  • Save samspills/5a85bc136e4378d5c3bc29d5dd93928b to your computer and use it in GitHub Desktop.
Save samspills/5a85bc136e4378d5c3bc29d5dd93928b to your computer and use it in GitHub Desktop.
cache that handles its own updates
case class BlerfCache(
blerfs: Ref[IO, Map[Id, Blerf]],
private val getBlerfMap: IO[Map[Id, Blerf]],
) extends Logging {
def updateBlerfs: IO[Unit] = getBlerfMap.flatMap(b => blerfs.set(b))
def refreshCache: IO[Unit] =
Stream
.repeatEval(logger.debug("refreshing blerf...") *> updateBlerfs)
.metered(5.minutes)
.compile
.drain
}
object BlerfCache {
def getBlerfMap(client: Client[IO]): IO[Map[Id, Blerf]] =
client
.expect[BlerfResp]("www.blerf.ca/fake/endpoint")
.flatMap(br => br.toBlerfMap)
def build(client: Client[IO]): Resource[IO, BlerfCache] = {
val blerf: IO[BlerfCache] = Ref.ofEffect(getBlerfMap(client)).map(BlerfCache(_, getBlerfMap(client)))
val updatingBlerf = Resource.eval(blerf).flatMap(b => b.refreshCache.background.map(_ => b))
updatingBlerf
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment