Skip to content

Instantly share code, notes, and snippets.

@notxcain
Created May 3, 2017 15:26
Show Gist options
  • Save notxcain/6de76dc1d1851bf8f356faf8d06b6d21 to your computer and use it in GitHub Desktop.
Save notxcain/6de76dc1d1851bf8f356faf8d06b6d21 to your computer and use it in GitHub Desktop.
Monix function cache with TTL
object Cache {
def apply[A, B](ttl: FiniteDuration)(f: A => Task[B]): A => Task[B] = {
val mvar = MVar(Map.empty[A, B])
a =>
for {
cached <- mvar.read.map(_.get(a))
out <- cached match {
case Some(b) => Task.pure(b)
case None =>
for {
cache <- mvar.take
b <- f(a)
_ <- Task.chooseFirstOf(mvar.put(cache.updated(a, b)),
mvar.take
.flatMap { x =>
mvar.put(x - a)
}
.delayExecution(ttl))
} yield b
}
} yield out
}
}
@Odomontois
Copy link

Odomontois commented Mar 2, 2018

So many reasons why this wouldn't work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment