Question

I've got the following method that retrieves from cache, or RESTfull API if it's a cache miss. I am having to use a flatMap so that I get a consistent interface.

Having to wrap the result of a cache hit in a future is bothering me a bit, since this MIGHT be expensive (if the library doesn't cater for this use-case).

Anyhow is this expensive ? and if so, whats the composition pattern for expressing the following without using a redundant future.

abstract class JsonApiQueryWithCache[T: FromResponseUnmarshaller] extends JsonApiQuery[T] {
  type fromCacheT = () => Future[Option[T]]
  type toCacheT = (T) => Int

  def fromCache: fromCacheT
  def toCache : toCacheT

  override def asCase(): Future[T] = {
    fromCache() flatMap  (_ match {
      // without the nested future: Future[T]
      case Some(x) => future {
        x
      }
      // : Future[Future[T]]
      case None =>
        super.asCase().map{ x=>
          toCache(x)
          x
        }
    })
  }
}
Was it helpful?

Solution

I would use Future.successful(x) instead of future { x }. This internally creates an instance of KeptPromise which is an already completed Future. I am not aware of any significant computational complexity related to this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top