How to create an Observable, which works only when there are subscribers, and gives the latest value to new subscribers immediately

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) // Fire an event every second
   .singleInstance() // Only do something when we have subscribers
   .startWith(null) // kick start as soon as something subscribes
   .flatMapLatest(interval => SomeAPI.someDataGet()) // get data, returns a promise

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) // Fire an event every second
   .singleInstance() // Only do something when we have subscribers
   .startWith(null) // kick start as soon as something subscribes
   .flatMapLatest(interval => SomeAPI.someDataGet()) // get data
   .publish() // Make this a hot observable;

That, as I understand it, is to make dataStreama hot observable.

- . , DataStream , , .

RxJS, , , .

+4
1

.publish() .shareReplay(1).

+4

Source: https://habr.com/ru/post/1608791/


All Articles