Created
March 6, 2018 19:15
-
-
Save satorg/aa09a2a270f647fd8758312364b3b3bc to your computer and use it in GitHub Desktop.
memoizeExpiring
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
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