【发布时间】:2020-01-24 17:59:40
【问题描述】:
我不确定如何解释。 of() 方法返回的 observable 不是多播。 如果我们这样做:
const obs = of(Math.random()).pipe(tap(()=>console.log('side effect'));
obs.subscribe(console.log);
obs.subscribe(console.log);
obs.subscribe(console.log);
我们会看到 3 个副作用,但 3 个也是相等的值。为什么?通常会在每次订阅时重新计算 observables。
例如
new Observable(observer => observer.next(Math.random()))
将返回 3 个不同的值。 为什么使用静态“of”方法创建的 observable 表现不同?我不知道该如何解释。和 observables 缓存有关系吗?
编辑 这是一个帮助我证明的小例子,'of' observables 确实是按需加载的。
const obs = of(undefined).pipe(
map(() => Math.random())
);
甚至
const obs = of(Math.random).pipe(
map(random => random())
);
【问题讨论】:
-
这可能是因为您将调用
Math.random()的结果而不是函数本身传递给of函数。 -
Math.random()返回一个数字。当该数字“重新计算”时应该发生什么变化? -
Math.random()返回一个随机值并立即进行评估。所以of(Math.random())基本上就像of(0.123456)(或产生的任何随机值)。
标签: javascript caching rxjs