By using Http, we call a method that does a network call and returns an http observable:
getCustomer() {
return this.http.get('/someUrl').map(res => res.json());
}
If we take this observable and add multiple subscribers to it:
let network$ = getCustomer();
let subscriber1 = network$.subscribe(...);
let subscriber2 = network$.subscribe(...);
What we want to do, is ensure that this does not cause multiple network requests.
This might seem like an unusual scenario, but its actually quite common: for example if the caller subscribes to the observable to display an error message, and passes it to the template using the async pipe, we already have two subscribers.
What is the correct way of doing that in RxJs 5?
Namely, this seems to work fine:
getCustomer() {
return this.http.get('/someUrl').map(res => res.json()).share();
}
But is this the idiomatic way of doing this in RxJs 5, or should we do something else instead?
Note : As per Angular 5 new HttpClient
, the .map(res => res.json())
part in all examples is now useless, as JSON result is now assumed by default.
Best Answer
EDIT: as of 2021, the proper way is to use the
shareReplay
operator natively proposed by RxJs. See more details in below answers.Cache the data and if available cached, return this otherwise make the HTTP request.
Plunker example
This article https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html is a great explanation how to cache with
shareReplay
.