Question

I have got a db-access I would like to cache in my akka/spray-application. The db returns a Future[Option[X]].

I set up a lruCache and wrapped it araound my db-access.

What I would like to achieve is, to cache the Option only, if it is Some(X) and not, if it is None. In the latter case the data should be retrieved from the db again.

Alternativly I could fail the future if this would help...

So far I remove the Option from the cache again via map and recover if it is None or the future failed:

cache(key) {
      server.one[X](...)
}.map {
   case Some(x) => Some(x)
   case None => {
     cache.remove(key)
     None
  }
}.recover {
  case x => userCache.remove(key)
}

But this is very ugly, not to mention side-effects in the map, etc...

Thank you in advance,

Jens

Was it helpful?

Solution

If the future is failed, then the value will be removed from the cache: https://github.com/spray/spray/blob/master/spray-caching/src/main/scala/spray/caching/LruCache.scala#L79

So this should do it:

cache(key) { server.one[X](...).map(_.get) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top