对我来说,RxJs 5share()
运算符的工作原理并不是 100% 清楚,请参阅此处的最新文档。Jsbin 的问题在这里。
如果我用一系列 0 到 2 创建一个 observable,每个值间隔一秒:
var source = Rx.Observable.interval(1000)
.take(5)
.do(function (x) {
console.log('some side effect');
});
如果我为这个 observable 创建两个订阅者:
source.subscribe((n) => console.log("subscriptor 1 = " + n));
source.subscribe((n) => console.log("subscriptor 2 = " + n));
我在控制台中得到了这个:
"some side effect ..."
"subscriptor 1 = 0"
"some side effect ..."
"subscriptor 2 = 0"
"some side effect ..."
"subscriptor 1 = 1"
"some side effect ..."
"subscriptor 2 = 1"
"some side effect ..."
"subscriptor 1 = 2"
"some side effect ..."
"subscriptor 2 = 2"
我以为每个订阅都会订阅同一个 Observable,但似乎并非如此!就像订阅的行为创建了一个完全独立的 Observable!
但是如果将share()
操作符添加到源 observable 中:
var source = Rx.Observable.interval(1000)
.take(3)
.do(function (x) {
console.log('some side effect ...');
})
.share();
然后我们得到这个:
"some side effect ..."
"subscriptor 1 = 0"
"subscriptor 2 = 0"
"some side effect ..."
"subscriptor 1 = 1"
"subscriptor 2 = 1"
"some side effect ..."
"subscriptor 1 = 2"
"subscriptor 2 = 2"
如果没有share()
.
这是怎么回事,share()
操作员是如何工作的?每个订阅是否都会创建一个新的 Observable 链?