我有从缓存中检索的以下方法,如果是缓存未命中,则使用RESTfull API。我不得不使用flatMap
,以便获得一致的界面。
必须在future
中包含缓存命中的结果让我感到困扰,因为这可能很昂贵(如果库不适合这个用例)。
无论如何这是昂贵的?如果是这样,那么表达以下内容的组合模式是什么,而不使用冗余的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
}
})
}
}
答案 0 :(得分:3)
我会使用Future.successful(x)
代替future { x }
。这在内部创建了KeptPromise
的实例,这是一个已经完成的Future。我不知道与此相关的任何重大计算复杂性。