Its not 100% clear for me how the RxJs 5 share()
operator works, see here the latest docs. Jsbin for the question here.
If I create an observable with a series of 0 to 2, each value separated by one second:
var source = Rx.Observable.interval(1000)
.take(5)
.do(function (x) {
console.log('some side effect');
});
And if I create two subscribers to this observable:
source.subscribe((n) => console.log("subscriptor 1 = " + n));
source.subscribe((n) => console.log("subscriptor 2 = " + n));
I get this in the console:
"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"
I thought each subscription would subscribe to the same Observable, but it does not seem to be the case! Its like the act of subscribing creates a completely separate Observable!
But if the share()
operator is added to the source observable:
var source = Rx.Observable.interval(1000)
.take(3)
.do(function (x) {
console.log('some side effect ...');
})
.share();
Then we get this:
"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"
Which is what I would expect without the share()
.
Whats going on here, how does the share()
operator work ? Does each subscription create a new Observable chain?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…