1

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.

here is a stackblitz with the code

Arikael
  • 1,989
  • 1
  • 23
  • 60

1 Answers1

1

Every time you call the method getData() it is returning a new observable - it doesn't matter that you've converted a cold observable to a hot one.

A more appropriate use of .publishReplay is to keep the same instance of the Observable.

For example:

export class TestService {
  data: Observable<any>;
  constructor(private http: HttpClient) {
     this.data = this.getData();
  }
  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:

this.data.subscribe(t=> ...);
this.data.subscribe(t=> ...);
Michael Kang
  • 52,003
  • 16
  • 103
  • 135