0

I have a button witch makes a request to the server. And i'm using the switchMap operator with subject for preventing multiple pending requests.

//service
  public getPhotos(): Observable<any> {
    return this.http.get<any>(`url`)
  }
//component
  private $filterSubject: Subject<void> = new Subject();
  public onFetchNewImage(): void {
    this.$filterSubject
      .pipe(
        switchMap(event => {
          return this.photoFetchService.getPhotos();
        })
      )
      .subscribe((photo) => {
        console.log('url', photo);
      })
      this.$filterSubject.next();
  }

But, more i click, more i make multiple requests, because my subject.observables array gets bigger each time i make a request subject log

here is my code: you can see console.log, stackblitz

2 Answers2

1

Since you added subscription inside click method, each click, add new subsciption to stack.you can avoid this by moving the subscribe code inside ngOnInit.

Try this:

component.ts

ngOnInit() {
  this.$filterSubject
      .pipe(
        switchMap(event => {
          return this.photoFetchService.getPhotos();
        })
      )
      .subscribe((photo) => {
        console.log('url', photo);
      })
}

 public onFetchNewImage(): void {  
    this.$filterSubject.next();
  }
mbojko
  • 13,503
  • 1
  • 16
  • 26
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
1

You keep the $filterSubject, and with every click you attach a new pipe with photoFetchService.getPhotos(), with a new subscription, to it, while all the old ones are still alive.

So: you click once: subscription no. 1 fires, you click again: new subscription no. 2 fires and the first one also fires... And so on. You can fix it for example with the take operator

    this.$filterSubject
      .pipe(
        switchMap(event => {
          return this.photoFetchService.getPhotos();
        }),
        take(1),
      )
      .subscribe(photo => {
          console.log('url', photo);
      });

or rethink the construction.

mbojko
  • 13,503
  • 1
  • 16
  • 26