I a using angular 4 for one of my projects and i am making a http call to get the data. I cache the data when the data is returned from the backend so that for the subsequent requests i dont have to make the rest calls again and again.
getApplication(): Observable<Array<Application>> {
return new Observable<Array<Application>>((observer) => {
if (this.app&& this.app.length > 0) {
observer.next(this.app)
} else {
this._http
.get<Application[]>(this.url)
.map((app) => this.mapToApp(app))
.subscribe((result: Array<Application>) => {
observer.next(result);
}, () => {
observer.next([]);
})
}
})
}
This works perfectly fine. But if two calls go at the same time, i see there are two requests going in the network tab instead of one. So i tried share() to make satisfy 'One observable, multiple subscribers'.
getApplication(): Observable<Array<Application>> {
return new Observable<Array<Application>>((observer) => {
if (this.app&& this.app.length > 0) {
observer.next(this.app)
} else {
this._http
.get<Application[]>(this.url)
.map((app) => this.mapToApp(app))
.subscribe((result: Array<Application>) => {
observer.next(result);
}, () => {
observer.next([]);
})
}
}).share()
}
But this also, i see there are multiple requests going in the network tab instead of one. What has to be done to make only one call and share the result with all the subscribers ? Please help.
Behavior Subject
which publishes its changes whennext
is called: github.com/Reactive-Extensions/RxJS/blob/master/doc/api/… – t3__rrySubject
internally which only multicasts values to an observer if they were already subscribed at the time. So if something subscribes, takes a value and then something else subscribes it won't get that same value. Essentiallyshare
allows the first one to steal!ShareReplay(1)
fixes this. I've foundshare
most useful when you have a connectable observable that doesn't start until you've made sure all the subscribers have subscribed - then you canshare
all you want in that case. – Simon_Weaver