Last active
April 21, 2023 18:14
-
-
Save samspills/5a85bc136e4378d5c3bc29d5dd93928b to your computer and use it in GitHub Desktop.
cache that handles its own updates
This file contains 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
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