Skip to content

Instantly share code, notes, and snippets.

@otobrglez
Created September 20, 2021 21:05
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 otobrglez/e7048262d5f2638a29739b26c3fcc3db to your computer and use it in GitHub Desktop.
Save otobrglez/e7048262d5f2638a29739b26c3fcc3db to your computer and use it in GitHub Desktop.
Playing around with caching with Cats Effect
final case class SimpleCache() {
private def tempDir(key: String): IO[Path] =
IO.fromTry(Try(System.getProperty("java.io.tmpdir")).map(s => Paths.get(s, key)))
private def serialize[V](path: Path)(v: V): Unit = {
val out = new ObjectOutputStream(new FileOutputStream(path.toString))
out.writeObject(v)
out.close()
}
private def deserialize[V](path: Path): V = {
val in = new ObjectInputStream(new FileInputStream(path.toString))
val obj = in.readObject()
in.close()
obj.asInstanceOf[V]
}
def fetch[V](key: String)(f: => IO[V]): IO[V] =
for {
cachePath <- tempDir(s"cache-${key}")
result <- IO(cachePath.toFile.exists()).flatMap {
case true =>
IO.println(s"Loading from path ${cachePath}") *>
IO(deserialize[V](cachePath))
case false =>
f.map { value =>
serialize[V](cachePath)(value)
value
}
}
} yield result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment