Search code examples
angularangular2-observablesangular-httpclient

Angular 2 HttpClient requires .subscribe


I pass a method that looks like this:

add = (): Observable<MatDialogRef<W, any>> => {
  let obs$ = this.service.getNew$().pipe(map(result => {
    this.applyNewItemProperties(result);
    return this.openDialog(result);
  }));

  obs$.subscribe();

  return obs$;
}

getNew$() is essentially a call to return HttpClient.get<T>.

My question is: Is this ok? I don't need the subscription, other than the fact that without it, the get doesn't fire. Do I need to unsubscribe() somewhere? Am I missing a better pattern?


Solution

  • You need a subscription somewhere because without it, your observable remains cold. Observable's are lazy, they don't do work until someone cares about the answer (making them hot). So yes, its ok (and expected) although I would question why nothing up the chain is subscribing to obs$ given that you are returning it.

    Strictly speaking, you don't need to unsubscribe as both those methods should be completing their Observable. You only need to unsubscribe if the observable is still hot but you no longer care about the results.