rxjs:缓存不同的http请求

时间:2019-02-04 14:13:50

标签: rxjs rxjs6 rxjs-pipeable-operators

此问题已移至“代码审查”:

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


关于使用rxjs缓存http请求的讨论很多,在这个问题/建议中,我想提出一个自定义的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));

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

非常欢迎对此自定义运算符有任何意见或建议!

0 个答案:

没有答案