Created
May 3, 2017 15:26
-
-
Save notxcain/6de76dc1d1851bf8f356faf8d06b6d21 to your computer and use it in GitHub Desktop.
Monix function cache with TTL
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So many reasons why this wouldn't work