I'm trying to understand rxjs publishReplay
, refCount
and share
What I wanted to achieve was caching of a http request as described here What is the correct way to share the result of an Angular Http network call in RxJs 5?
Here's what I came up with
export class TestService {
constructor(private http: HttpClient) {}
getData(): Observable<any> {
return this.http.get('https://httpbin.org/anything').map((data: any) => {
console.log('getting data');
return Math.floor(Math.random() * 20);
}).publishReplay(1).refCount();
}
}
calling it
t.getData().subscribe((data: any) => console.log(data));
t.getData().subscribe((data: any) => console.log(data));
the request will usually made twice.
Just to unterstand the cause of this:
Am I correct that this behavior occurs if the observable (http request) hasn't completed yet when I subscribe a second time?
If I move the seccond t.getData()
inside the the first subscriptions next only one request is mode.