1

我在容器中有一个缓存方法:

get(): Observable<T[]> {
  if (!this.get$) {
    this.get$ = merge(
      this.behaviorSubject.asObservable(),
      this._config.get().pipe(shareReplay(1), tap(x => this.behaviorSubject.next(x))));
  }

  return this.get$;
}

这适用于普通的可观察对象,但是当我在myContainer2中缓存波纹管(例如,使用缓存的可观察对象的结果创建另一个缓存的可观察对象)方法时,例如:

// get is assigned to _config.get in the above function
const myContainer2 = new Container({get: () => myContainer1.get().pipe(mergeMap(res1 => getObs2(res1))});

// please note, the end goal is to resolve the first observable on the first subscription 
// and not when caching it in the above method (using cold observables)
myContainer2.get().subscribe(...) // getObs2 gets called
myContainer2.get().subscribe(...) // getObs2 gets called again
myContainer2.get().subscribe(...) // getObs2 gets called for a third time, and so on

每次订阅getObs2的第二个缓存都会被调用(它什么都不缓存)。我怀疑我的 get 实现是错误的,因为我正在合并一个行为主题(它在开始时发出),但我想不出任何其他方式来实现它(为了使用冷的 observables)。请注意,如果我使用普通的 observable 而不是 myContainer.get() 一切都会按预期工作。你知道问题出在哪里吗?

4

1 回答 1

1

使用声明性方法,您可以按如下方式处理缓存:

// Declare the Observable that retrieves the set of 
// configuration data and shares it.
config$ = this._config.get().pipe(shareReplay(1));

订阅 config$ 时,如果尚未检索到配置,上述代码将自动获取配置或返回检索到的配置。

我不清楚 BehaviorSubject 代码在您的示例中的用途。如果要保存发出的配置数据,则没有必要,因为config$它将提供它。

于 2021-08-18T22:10:03.400 回答