0

此问题已移至 Code-Review:

https://codereview.stackexchange.com/questions/212854/rxjs-caching-different-http-requests


关于使用 rxjs 缓存 http-requests 已经进行了多次讨论,在这个问题/建议中,我想提出一个自定义 rxjs-operator(非纯)来提供缓存:

const cacheHttp = (cacheKey: string, cacheStorage: any) => (source: Observable<any>) => {
  if (!cacheStorage[cacheKey]) {
    cacheStorage[cacheKey] = source.pipe(
      shareReplay(1)
    );
  }
  return cacheStorage[cacheKey];
};

这个操作符不是纯粹的,因为它修改了它的一个参数(cacheStorage)。

该运算符可以这样使用:

public cachedItems = {};

public getDataForItem$(itemId: string) {
    return this.http.get('/item/' + itemId).pipe(
        cacheHttp(itemId, this.cachedItems),
        shareReplay(1)
    );
}

然后客户端可以多次调用它而不会导致多余的 http 请求:

// the following two subscriptions cause http-requests
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));

// all further subscriptions would not cause any additional http-requests
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));

// this subscription would again cause an http-request:
this.itemService.getDataForItem('thirdItem').subscribe((val) => console.log(val));

现在我的问题是: 这是解决“不同请求缓存问题”的可接受方法吗?是否可能存在内存泄漏或是否有任何泄漏的订阅?可以对提供的参数产生副作用吗?

非常欢迎对此自定义运算符的问题提出任何意见或提示!

4

0 回答 0