当您订阅 observable 时,它会因为缺少更好的词而“运行”。随着值随着时间的推移而分散,这可能会变得有点令人困惑,所以我们将坚持使用同步调用。考虑以下可观察的。
const getRandom = () => Math.floor(Math.random() * 10);
const stream$ = defer(() => from([getRandom(), getRandom(), getRandom()]));
stream$.subscribe(console.log); // 4 6 2
stream$.subscribe(console.log); // 4 4 2
stream$.subscribe(console.log); // 1 8 6
stream$.subscribe(console.log); // 8 6 7
注意每个订阅如何获得不同的数字?他们都在重新运行getRandom(),并且他们的订阅获得不同的值。
如果我们在stream$ 中放置一个累加器,每个订阅都将从一个新种子开始,并根据其流发出的内容获得结果。
所以:
const getRandom = () => Math.floor(Math.random() * 10);
const stream$ = defer(
() => from([getRandom(), getRandom(), getRandom()])
).pipe(
reduce((acc, val) => acc + val, 0)
);
stream$.subscribe(console.log); // 12 (4+6+2)
stream$.subscribe(console.log); // 10 (4+4+2)
stream$.subscribe(console.log); // 15 (1+8+6)
stream$.subscribe(console.log); // 21 (8+6+7)
查看每个订阅如何不添加到前一个订阅?它只是将自己的数字相加。
他们不会在不同订阅之间共享累加器或值或任何东西。
那么当你使用像shareReplay() 这样的东西时会发生什么?在这种情况下,stream$ 不会被订阅并“运行”4 次不同的时间,而是只订阅一次,并且无论之后有多少人订阅,单次订阅的结果都会共享。
const getRandom = () => Math.floor(Math.random() * 10);
const stream$ = defer(
() => from([getRandom(), getRandom(), getRandom()])
).pipe(
reduce((acc, val) => acc + val, 0),
shareReplay(1)
);
stream$.subscribe(console.log); // 12 (4+6+2)
stream$.subscribe(console.log); // 12
stream$.subscribe(console.log); // 12
stream$.subscribe(console.log); // 12
在这里,我们的累加器只运行一次。
如果你像这样改变它:
const getRandom = () => Math.floor(Math.random() * 10);
const stream$ = defer(
() => from([getRandom(), getRandom(), getRandom()])
).pipe(
shareReplay(3),
reduce((acc, val) => acc + val, 0)
);
stream$.subscribe(console.log); // 12 (4+6+2)
stream$.subscribe(console.log); // 12 (4+6+2)
stream$.subscribe(console.log); // 12 (4+6+2)
stream$.subscribe(console.log); // 12 (4+6+2)
然后累加器运行 4 次,但只调用 getRandom() 来创建前 3 个值,之后每个订阅都会获得相同的 3 个数字。
所以,回答你的问题:
如果您没有 shareReplay,每个订阅者都会在订阅时开始运行自己的 scan 流。 与 shareReply,scan 仅订阅一次。您将这些结果多播给所有未来的订阅者。这就是区别。