使用 RxJS(和 Angular)临时缓存来自参数化请求的 HTTP 响应

Lau*_*ens 6 rxjs angular

我想缓存和过期来自例如具有某些参数的 GET 请求的 HTTP 响应。

用例示例:

假设我构建了一个这样的服务:

@Injectable()
export class ProductService {

  constructor(private http: HttpClient) {}

  getProduct$(id: string): Observable<Product> {
    return this.http.get<Product>(`${API_URL}/${id}`);
  }

  getProductA$(id: string): Observable<ProductA> {
    return this.getProduct$(id).pipe(
      // bunch of complicated operations here
    };
  }

  getProductB$(id: string): Observable<ProductB> {
    return this.getProduct$(id).pipe(
      // bunch of other complicated operations here
    };
  }

}
Run Code Online (Sandbox Code Playgroud)

现在无论出于何种原因,在组件 A 中调用函数 A,在组件 B 中调用函数 B。我知道这可以通过另一种方式完成(例如顶级智能组件获取 HTTP 数据并通过输入参数传递它) ,但无论出于何种原因,这两个组件都是“智能”的,它们各自调用一个服务函数。

两个组件都加载在同一页面上,因此会发生两次订阅 = 对同一端点的两次 HTTP 请求 - 即使我们知道结果很可能是相同的。

我想简单地缓存 的响应getProduct$,但我也希望这个缓存很快过期,因为产品管理部门的 Margareth 将在 2 分钟内更改产品价格。

我试过但不起作用:

基本上,我尝试使用 shareReplay 保留一个热观察值字典,窗口时间为 5 秒。我的假设是,如果(源)observable 完成或订阅数为 0,那么下一个订阅者将简单地重新触发 observable,但情况似乎并非如此。

private product$: { [productId: string]: Observable<Product> } = {};

getProduct$(id: string): Observable<Product> {
  if (this.product$[id]) {
    return this.product$[id];
  }
  this.product$[id] = this.http.get<Product>(`${API_URL}/${id}`)
    .pipe(
      shareReplay(1, 5000), // expire after 5s
    )
  );
  return this.product$[id];
}
Run Code Online (Sandbox Code Playgroud)

我想,我可以尝试使用 finalize 或 finally 在完成时从我的字典中删除 observable,但不幸的是,每次取消订阅时也会调用这些。

所以解决方案可能更复杂。

有什么建议?

mar*_*tin 14

如果我理解正确,你想根据他们的id参数缓存响应,所以当我getProduct()用不同的ids创建两个时,我会得到两个不同的未缓存结果。

我认为最后一个变体几乎是正确的。您希望它取消订阅其父级,以便稍后重新订阅和刷新缓存值。

shareReplay如果我没记错的话,操作符在 RxJS 5.5 之前的工作方式有所不同,如果我shareReplay没有重新订阅它的源代码。它后来在 RxJS 6.4 中重新实现,您可以根据传递给shareReplay. 由于您正在使用shareReplay(1, 5000)它似乎您正在使用 RxJS <6.4,因此最好使用publishReplay()andrefCount()运算符代替。

private cache: Observable<Product>[] = {}

getProduct$(id: string): Observable<Product> {
  if (!this.cache[id]) {
    this.cache[id] = this.http.get<Product>(`${API_URL}/${id}`).pipe(
      publishReplay(1, 5000),
      refCount(),
      take(1),
    );
  }

  return this.cache[id];
}
Run Code Online (Sandbox Code Playgroud)

请注意,我还包括take(1). 那是因为我希望链在publishReplay发出缓冲区之后和订阅源 Observable 之前立即完成。没有必要订阅它的源,因为我们只想使用缓存的值。5 秒后,缓存的值将被丢弃,publishReplay并将再次订阅其源。

我希望这一切都有意义:)。

  • 链接到以下存储库评论,因为,AFAICT,“5 秒后缓存的值被丢弃,`publishReplay` 将再次订阅其源”行为取决于 RxJS 版本 7 中修复的错误:https://github.com /ReactiveX/rxjs/issues/6260#issuecomment-826588604 (2认同)