spray-cache: cache only when not None

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

Answers


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) }

Need Your Help

XmlSerializer throws exception when serializing dynamically loaded type

c# reflection serialization

I'm trying to use the System.Xml.Serialization.XmlSerializer to serialize a dynamically loaded (and compiled class). If I build the class in question into the main assembly, everything works as exp...