I am trying to create a thread / observable that ...
- Only events when he has subscribers
- Provides new subscribers with the latest value.
The specific case is that I need an observation that calls the Async API call whenever a particular event occurs, but only if it has subscribers. I am trying to avoid unnecessary API calls.
I managed to create a thread that only fires when it has such subscribers ...
let dataStream = Rx.Observable
.interval(1000)
.singleInstance()
.startWith(null)
.flatMapLatest(interval => SomeAPI.someDataGet())
And it works. If I'm console.log(...)in a method SomeAPI.someDataGet, I see that it fires when the thread has subscribers. And my implementation looks very good, because I do this to subscribe and unsubscribe, which fits very well with the React component life cycle methods.
let sub1;
sub1 = dataStream.subscribe(x => console.log('sub1', x));
sub1.dispose();
I also want new subscribers to receive the latest value at the moment they subscribe. I'm scared here. If I do this ...
let sub1, sub2;
sub1 = dataStream.subscribe(x => console.log('sub1', x));
setTimeout( () => {
sub2 = dataStream.subscribe(x => console.log('sub2', x));
}, 1500)
... I do not see console.logfor sub2until the next interval.
If my understanding is correct. I need a Hot Observable . So I tried to create such a stream ...
let dataStream = Rx.Observable
.interval(1000)
.singleInstance()
.startWith(null)
.flatMapLatest(interval => SomeAPI.someDataGet())
.publish()
That, as I understand it, is to make dataStreama hot observable.
- . , DataStream , , .
RxJS, , , .