【发布时间】:2021-03-22 15:39:27
【问题描述】:
这是重现问题的最少代码:
import { defer, BehaviorSubject, of } from "rxjs";
import { shareReplay, switchMap } from "rxjs/operators";
const oneRandomNumber = defer(() => of(Math.floor(Math.random() * 20)));
const cache = { key: oneRandomNumber.pipe(shareReplay(1)) };
export const swr = () =>
new BehaviorSubject(null).pipe(
switchMap(() => cache.key),
switchMap(number => {
console.log(number); // WHY DOES THIS EXECUTE SO MANY TIMES?!
return cache.key;
})
);
swr().subscribe();
我希望只看到一个记录的数字。不是数百个。
如果您执行以下任何操作,问题就会消失:
- 删除
shareReplay(1) - 你不使用
cache对象,直接使用oneRandomNumber.pipe(shareReplay(1)) - 不要使用
switchMap两次
但我的最终代码需要所有这些东西。
【问题讨论】:
-
我看到你的演示正在使用 rxjs
7.0-beta;切换到6.6.4可以解决问题。 -
嗯,你是对的。好的,我刚刚报告了错误并返回到版本 6。
标签: javascript rxjs