I have a piece of code I'd like to execute periodically until all subscribers have unsubscribed.
// This function shall be called *once* per tick,
// no matter the quantity of subscriber.
function doSomething(val) {
console.log("doing something");
return val;
}
observable = Rx.Observable.timer(0, 1000).map(val => doSomething(val));
const first = observable.subscribe(val => console.log("first:", val));
const second = observable.subscribe(val => console.log("second:", val));
// After 1.5 seconds, stop first.
Rx.Observable.timer(1500).subscribe(_ => first.unsubscribe());
// After 2.5 seconds, stop second.
Rx.Observable.timer(2500).subscribe(_ => second.unsubscribe());
JSFiddle
My expected output would look like that:
doing something
first: 0
second: 0
doing something
first: 1
second: 1
doing something
second: 2
<nothing more>
However, the doSomething
function is called twice when the two observable are called. Here is the actual output:
doing something
first: 0
doing something
second: 0
doing something
first: 1
doing something
second: 1
doing something
second: 2
<nothing more>
Am I doing a design mistake? Is there a way to do this?
The behaviour you are seeing is correct. The observable returned by interval
is cold. That is, no timer is created until an observer subscribes and, when one does, the timer that's created is specifically for that subscription.
The behaviour you were expecting can be effected using the share
operator:
observable = Rx.Observable
.timer(0, 1000)
.map(val => doSomething(val))
.share();
The share
operator reference counts subscriptions and multicasts the source observable to multiple subscribers - so there will be only a single interval/timer, shared between the two subscribers.
For more information, you might find this article useful.
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