I cannot share my Observable stream properly and my http request calls twice

Viewed 46

Hey I have a problem with share operator. When I use async pipe with data$ and totalElements$ my http request executes twice. I wish it would execute only once. I tried to use shareReplay istead and It did not work as well.

filters$: BehaviorSubject<any> = ...
...

getComplaints() {
  return this.filters$.pipe(
    flatMap(filters => {
      this.loading = true;
      return this.complaintService
        .getComplaints$(filters)
        .pipe(
          finalize(() => this.loading = false),
          share()
        );
      })
    );
 }

this.data$ = this.getComplaints().pipe(map(value => value.pageItems));
this.totalElements$ = this.getComplaints().pipe(map(value => value.totalItems));
1 Answers

For share to work you have to create only one observable (so don't use a function) and put the operator on the outer observable. You'll probably want to use shareReplay so that late subscribers get the latest value.

this.complaints$ = this.filters$.pipe(
  flatMap(filters => {
    this.loading = true;
    return this.complaintService
      .getComplaints$(filters)
      .pipe(
        finalize(() => this.loading = false),
      );
    }),
  shareReplay(1)
);

this.data$ = this.complaints$.pipe(map(value => value.pageItems));
this.totalElements$ = this.complaints$.pipe(map(value => value.totalItems));
Related