我开发了一个 Angular 9 应用程序,但我不明白如何将shareReplay运算符与其他运算符一起使用。我做了类似以下的事情:
if (!this.cache[key]) {
this.cache[key] = this.http.get(...).pipe(
shareReplay(1),
flatMap(...),
map(...),
reduce(...)
);
}
return this.cache[key];
在此之后,我的应用程序卡住了 100% 的 CPU 使用率。当我将其更改为:
if (!this.cache[key]) {
this.cache[key] = this.http.get(...).pipe(
flatMap(...),
map(...),
reduce(...),
shareReplay(1)
);
}
return this.cache[key];
它似乎工作正常。是否有必要使用shareReplay运算符作为最后一个?这么高的 CPU 使用率从何而来?
编辑:更详细的代码片段:
this.http.get(...).pipe(
// I would like to avoid several same http calls
shareReplay(1),
// I would like to flatten an array of objects that comes from backend
flatMap(option => option),
// I need to map all objects to a format that is acceptable by some library
map(option => ({
value: option.key,
label: option.value
})),
// I must reduce it back to an array of the new objects
reduce((acc: { value: string; label: string }[], option) => {
acc.push(option);
return acc;
}, [])
);