Last active
August 29, 2015 14:25
-
-
Save mikesname/fe85deeea9553b4c496c to your computer and use it in GitHub Desktop.
Caching a Future[T]
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 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