Angular/RxJs - Unsubscribing dependent http services using take(1)?

Viewed 72

--Component.ts--

 getGenCoreLabs() {
    this.checkinService
      .getLaboratories()
      .pipe(
        switchMap(outerResp => {
          const total = outerResp.headers.get(outerResp.headers.get('total'));
          return this.checkinService.getGenCoreLabs(total);
        }),
        take(1)
      )
      .subscribe(resp => {
        this.apiResponse = resp;
        this.areaList = this.apiResponse.map(labName => {
          return labName.Name;
        });
        this.areaListIds = this.apiResponse.map(labGuid => {
          return labGuid.Guid;
        });
      });
  }

In the code above inside my component.ts file, is a single take(1) enough to unsubscribe from the dependent http services? Or do i have to call take(1) inside the second service(getGenCoreLabs) in service.ts file as well? ( please see the below code for reference)

--Service.ts--

public getGenCoreLabs(total: number): Observable<CoreLaboratoryData> {
    const url = `/core/laboratories?per-page=${total}`;
    return this.httpService.get(url).pipe(take(1));
  }

2 Answers

An Observable can do 3 things: notify, error and complete.

Once an Observable errors or completes, it can not resume any more, i.e. it can NOT notify any more values. You do not need to unsubscribe subscriptions on Observables that have errored or completed, since they can not emit any more. You need to unsubscribe subscriptions on Observables that you know can notify again, if you are not interested any more in processing such notifications.

If you model an http request as an Observable, as in Angular, what you have is an Observable that can do just one of these 2 things:

  1. Notifies the response when it arrives and then completes
  2. Errors if something goes wrong

In both cases the Observable will not notify any more, so you do not need to unsubscribe.

You may take a look at this answer for more details.

You don't need to unsubscribe when the observable is a finite sequence. It's the case for a HTTP request, which will emit only one value.

Same case for example with timer(1000) which emits one value after 1000 ms only.

For more details on different situations when you should unsubscribe or you don't need to unsubscribe, check When to Unsubscribe in Angular by Netanel Basal.

So your code could be:

getGenCoreLabs() {
  this.checkinService.getLaboratories().pipe(
    switchMap(outerResp => {
      const total = outerResp.headers.get(outerResp.headers.get('total'));
      return this.checkinService.getGenCoreLabs(total);
    }),
  ).subscribe(resp => {
    ...
  })
}
Related