Why is the map operator evaluated for each subscriber instead of once?
const obs1 = Rx.Observable.interval(1000).take(1).map((x, i) => {
console.log(i+1 + ':1 map')
return 'obs1';
})
const obs2 = Rx.Observable.interval(1300).take(1).map((x, i) => {
console.log(i+1 + ':2 map')
return 'obs2';
})
const obs3 = Rx.Observable.interval(1700).take(2).map((x, i) => {
console.log(i+1 + ':3 map')
return 'obs3';
})
const view = obs1.combineLatest(obs2, obs3, (obs1, obs2, obs3) => { return obs1 + ', ' + obs2 + ', ' + obs3; });
// Every subscriber adds more calls to map - why is it called multiple times at the same time ?
view.subscribe((value) => {
console.log('sub1: ' + value)
});
view.subscribe((value) => {
console.log('sub2: ' + value)
});
view.subscribe((value) => {
console.log('sub3: ' + value)
});
I created a testcase here: http://jsbin.com/jubinuf/3/edit?js,console
Can I write this testcase differently to avoid this behaviour?
get(apiURL) returns an Observable . map is an observable operator which calls a function for each item on its input stream and pushes the result of the function to its output stream. In this case each input item is a Response object.
RxJS map() operator is a transformation operator used to transform the items emitted by an Observable by applying a function to each item. It applies a given project function to each value emitted by the source Observable and then emits the resulting values as an Observable.
The Map operator applies a function of your choosing to each item emitted by the source Observable, and returns an Observable that emits the results of these function applications.
do() is to execute code for each event. A difference to . map() is, that the return value of . do() is ignored and doesn't change what value the subscriber receives.
Every subscriber will run through the Observable sequence. If you want everyone to get the resulting stream instead, use .publish().refCount()
.
http://jsbin.com/ditikonopi/edit?js,console
The .publish()
will return an observable sequence that shares a single subscription to the underlying sequence. refCount()
will stay connected to the source so long as there is at least one subscription.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With