Skip to content

Instantly share code, notes, and snippets.

@mikesname
Created October 19, 2015 07:32
Show Gist options
  • Save mikesname/f8bb6be8e950511db1d4 to your computer and use it in GitHub Desktop.
Save mikesname/f8bb6be8e950511db1d4 to your computer and use it in GitHub Desktop.
package utils.caching
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)(orElse : => 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 = orElse
value.map { a =>
cache.set(key, a, expiration)
a
}
}
}
def set[A](key: String, expiration: Duration = Duration.Inf)(get: => Future[A])(implicit cache: CacheApi, ct: ClassTag[A], executionContext: ExecutionContext): Future[A] = {
val value = get
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