Skip to content

Instantly share code, notes, and snippets.

@mikesname
Last active August 29, 2015 14:25
Show Gist options
  • Save mikesname/fe85deeea9553b4c496c to your computer and use it in GitHub Desktop.
Save mikesname/fe85deeea9553b4c496c to your computer and use it in GitHub Desktop.
Caching a Future[T]
import scala.concurrent.duration.Duration
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag
import play.api.cache.CacheApi
object FutureCache {
def getOrElse[A](key: String, expiration: Duration = Duration.Inf)(f: => Future[A])(implicit cache: CacheApi, ct: ClassTag[A], executionContext: ExecutionContext): Future[A] = {
cache.get[A](key) match {
case Some(a) => Future.successful(a)
case _ =>
val value = f
value.map { a =>
cache.set(key, a, expiration)
a
}
}
}
def set[A](key: String, expiration: Duration = Duration.Inf)(f: => Future[A])(implicit cache: CacheApi, ct: ClassTag[A], executionContext: ExecutionContext): Future[A] = {
val value = f
value.map { a =>
cache.set(key, a, expiration)
a
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment