對於我來說,它不是100%清楚如何RxJs 5 share()
操作員工作,請參閱這裏latest docs。 Jsbin的問題here。RxJs 5 share()運算符是如何工作的?
如果我創建一個可觀察到的一系列的0至2,一秒分隔每個值:
var source = Rx.Observable.interval(1000)
.take(5)
.do(function (x) {
console.log('some side effect');
});
如果我創建了兩個訂戶此觀察到:
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()
經營者添加到源觀察到:
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鏈?