By using Http, we call a method that does a network call and returns an http observable:
getCustomer() {
return
I starred the question, but i'll try and have a go at this.
//this will be the shared observable that
//anyone can subscribe to, get the value,
//but not cause an api request
let customer$ = new Rx.ReplaySubject(1);
getCustomer().subscribe(customer$);
//here's the first subscriber
customer$.subscribe(val => console.log('subscriber 1: ' + val));
//here's the second subscriber
setTimeout(() => {
customer$.subscribe(val => console.log('subscriber 2: ' + val));
}, 1000);
function getCustomer() {
return new Rx.Observable(observer => {
console.log('api request');
setTimeout(() => {
console.log('api response');
observer.next('customer object');
observer.complete();
}, 500);
});
}
Here's the proof :)
There is but one takeaway: getCustomer().subscribe(customer$)
We are not subscribing to the api response of getCustomer()
, we are subscribing to a ReplaySubject which is observable which is also able to subscribe to a different Observable and (and this is important) hold it's last emitted value and republish it to any of it's(ReplaySubject's) subscribers.