Skip to content

Instantly share code, notes, and snippets.

@satorg
Created March 6, 2018 19:15
Show Gist options
  • Save satorg/aa09a2a270f647fd8758312364b3b3bc to your computer and use it in GitHub Desktop.
Save satorg/aa09a2a270f647fd8758312364b3b3bc to your computer and use it in GitHub Desktop.
memoizeExpiring
import monix.eval._
import monix.execution.atomic.Atomic
def memoizeExpiring[A](sourceTask: Task[A], interval: FiniteDuration): Task[A] = {
class State {
val memoizedTask: Task[A] = sourceTask.memoize
val deadline: Deadline = interval.fromNow
}
val atomic = Atomic(new State)
@tailrec def loop(): State = {
val current = atomic.get
if (current.deadline.isOverdue) {
val update = new State
if (!atomic.compareAndSet(current, update)) loop() // retry
else update
} else {
current
}
}
Task.defer { loop().memoizedTask }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment