【问题标题】:Scala Future Composition KerfuffleScala 未来组合 Kerfuffle
【发布时间】:2014-04-15 11:18:49
【问题描述】:

我有以下从缓存中检索的方法,如果是缓存未命中,则为 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
        }
    })
  }
}

【问题讨论】:

    标签: multithreading scala concurrency parallel-processing future


    【解决方案1】:

    我会使用Future.successful(x) 而不是future { x }。这在内部创建了一个 KeptPromise 的实例,它是一个已经完成的 Future。我不知道与此相关的任何重大计算复杂性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2018-02-14
      • 2013-08-04
      • 1970-01-01
      • 2016-02-06
      • 2017-06-24
      相关资源
      最近更新 更多