user1693057 user1693057 - 2 months ago 15
TypeScript Question

Multiple Api requests

I store a stream as a variable then subscribe to it 3 times.

As I imagined it at first, it will perform an action then at the end get the data next it triggers and everybody will get its one update. It was wrong because it performs an action for every subscriber, means many API calls in this case. If I create a Subject then subscribe with it to the Observer and make anybody else to subscribe to this Subject then it works.
Unfortunately, I am new in RP could you explain to me what is happening here?

this.listStream = Observable
.interval(this.refreshInterval)
.do(() => console.log('call the api 3 times'))
.map(i => fruitApiStream)
.startWith(fruitApiStream)
.flatMap<FruitDto[]>(s => s)
.map<Fruit[]>(
s => s.map(s => {
return new Fruit(s.fruitId, s.name);
}));

Answer

The issue here that you encounter is a typical one. That behaviour is due to the fact that rxjs streams are 'cold' by default. That means that every subscriber will start the producer anew, hence the repetition that you observe. Subjects are 'hot', hence the fact that you do not observe the repetition.

You should dig at some point into understanding the stream temperature metaphor, because the more you use streams the more you will have to deal with these issues.

The simple fix is to use the share operator:

this.listStream = Observable
            .interval(this.refreshInterval)
            .do(() => console.log('call the api 3 times'))
            .map(i => fruitApiStream)
            .startWith(fruitApiStream)
            .flatMap<FruitDto[]>(s => s)
            .map<Fruit[]>(
            s => s.map(s => {
                return new Fruit(s.fruitId, s.name);
            }))
            .share();

For a similar question (and answer), have a look here :

For a better understanding of hot vs. cold, have a look here :

For details on subjects, and their semantics, you can look here :