Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guizmaii/69a7b9d56b126f47c5b11353838601a5 to your computer and use it in GitHub Desktop.
Save guizmaii/69a7b9d56b126f47c5b11353838601a5 to your computer and use it in GitHub Desktop.
import cats.effect.ExitCode
import monix.eval.{Task, TaskApp}
import monix.execution.atomic.Atomic
class MtCache[A](ref: Atomic[Map[String, Task[A]]]) {
def cache(key: String)(task: () => A): Task[A] = {
ref.transformAndExtract { current =>
current.get(key) match {
case None =>
val inst = Task.evalOnce(task())
(inst, current.updated(key, inst))
case Some(value) =>
(value, current)
}
}
}
}
object TryMtCache extends TaskApp {
override def run(args: List[String]): Task[ExitCode] = {
val cc = new MtCache[Long](Atomic(Map[String, Task[Long]]()))
val first = () => {
System.err.println("start eff1")
System.err.println("sleeping eff1")
Thread.sleep(500L)
System.err.println("finish eff1")
System.currentTimeMillis()
}
val second = () => {
System.err.println("start eff2")
System.err.println("sleeping eff2")
Thread.sleep(300L)
System.err.println("finish eff2")
System.currentTimeMillis()
}
val third = () => {
System.err.println("start eff3")
System.err.println("sleeping eff3")
Thread.sleep(100L)
System.err.println("finish eff3")
System.currentTimeMillis()
}
val t1 = cc.cache("first")(first).map(v => "First:" + v)
val t2 = cc.cache("second")(second).map(v => "Second:" + v)
val t3 = cc.cache("third")(third).map(v => "Third:" + v)
Task.gather(t1 :: t2 :: t1 :: t2 :: t3 :: Nil).map { s =>
s.foreach(r => println(r))
ExitCode.Success
}
}
}
import monix.eval.Coeval
import monix.execution.atomic.Atomic
class CCache[A](ref: Atomic[Map[String, Coeval[A]]]) {
def cache(key: String)(task: () => A): Coeval[A] = {
ref.transformAndExtract { current =>
current.get(key) match {
case None =>
val inst = Coeval.evalOnce(task())
(inst, current.updated(key, inst))
case Some(value) =>
(value, current)
}
}
}
}
object TryCCache {
def main(args: Array[String]): Unit = {
val cc = new CCache[Long](Atomic(Map[String, Coeval[Long]]()))
val first = () => {
System.err.println("eff1")
System.currentTimeMillis()
}
val second = () => {
System.err.println("eff2")
System.currentTimeMillis()
}
val third = () => {
System.err.println("eff3")
System.currentTimeMillis()
}
println("First:" + cc.cache("first")(first).value())
println("Second:" + cc.cache("second")(second).value())
println("First:" + cc.cache("first")(first).value())
println("Second:" + cc.cache("second")(second).value())
println("Third:" + cc.cache("third")(third).value())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment