7

Is there a need to unsubscribe from the Observable the Angular HttpClient's methods return?

For example:

this.http.get(url).subscribe(x => this.doSomething());

Do I need to unsubscribe from this subscription? I am asking this is because I don't know if Angular handles it itself. Plus the request is one-off not continuously. I tend to think I don't need to. What are your thoughts?

As per the below post: Angular/RxJs When should I unsubscribe from `Subscription`

RxJS handles the one-off subscription but I didn't find anything in their doc.

Antediluvian
  • 653
  • 1
  • 6
  • 18
  • Maybe you can check the old question and see if it fits your question: https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods – Rinne Hmm Oct 18 '19 at 03:23
  • you don't need to unsubscribe it. It observes until getting a response from api. And once it gets it unsubscribes from the HTTP request you have sent. – sibabrat swain Oct 18 '19 at 03:24
  • @sibabratswain What if the user navigates away from the current component before the response comes back? – Antediluvian Oct 18 '19 at 03:55
  • @RinneHmm Thanks for the link. That is a lot of useful info. – Antediluvian Oct 18 '19 at 03:57
  • This should be marked as a duplicate, you have linked to the answer in your question. – Adrian Brand Oct 18 '19 at 04:43

4 Answers4

13

No, You don't need to unsubscribe it. It observes until getting a response from api. And once the Http request completes it unsubscribes automatically.

Refer to this

Why not to unsubscribe Http Observables

Angular guide http

AsyncPipe

sibabrat swain
  • 1,277
  • 8
  • 20
  • What if the user navigates away from this component before the response comes back? Do I need the `takeUntil()` pattern? – Antediluvian Oct 18 '19 at 03:56
  • 1
    Https uses AsyncPipe for the response and the async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. So it will automatically unsubscribe if you navigate between components. – sibabrat swain Oct 18 '19 at 04:04
  • @sibrat swain, `AsyncPipe` is limited to templates as far as I know. Quite often, I need to do complex stuff after I get the data from the server in which case the `AsyncPipe` won't suffice. – Antediluvian Oct 18 '19 at 04:39
  • @Antediluvian takeUntil() will work but I guess you don't need it here. Async pipe handles all that for you. That would be a good practice, instead of unsubscribing yourself let the pipe do that everything for you. It will not break your functionalities for complex operations. – sibabrat swain Oct 18 '19 at 05:28
1

You can unsubscribe from all Observables in your page at the 'same' time when your leave the page with ngOnDestroy. You pipe an Observable which is activated when you leave the page and closes the function.

export class X implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject();

  ngOnInit() {
    this.functionOne();
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  functionOne() {
    this.service
      .getData()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(
        (result) => {},
        (error) => {}
      );    
  }
}

Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45
0

There are 2 ways to handle this:

1) Yes, you have to unsubscribe manually if you are subscribing to observable normally in the ts file. usually we can do unsubscribe in the ngOnDestroy() life cycle method

2) If you use async pipe syntax on the observable in angular template, then it automatically close the subscription

observable | async 

Refer below: https://angular.io/api/common/AsyncPipe

Pradeep
  • 1,192
  • 2
  • 12
  • 30
  • 1
    He is asking only for `HttpClient` not other `BehaviorSubject` – sibabrat swain Oct 18 '19 at 03:29
  • I mean if the `Observable` is created by myself, then yes. I need to unsubscribe. But in this particular situation, `HttpClient` creates it for you. And I don't think Angular has got doco on whether I need to unsubscribe. – Antediluvian Oct 18 '19 at 03:56
  • It uses async pipe to get the response and the async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. – sibabrat swain Oct 18 '19 at 05:20
0

Yes, it is necessary to unsubscribe it according to https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0

Here is what I do:


export class CustomerSummaryComponent implements OnInit, OnDestroy {
  subscriptions: Subscription[];

  ngOnInit() {
    this.subscriptions = [];

    this.subscriptions.push(
        this.customerService.getCustomer(this.customerId).subscribe(
        data => {
        },
        error => {
            console.log(error);
        }
        )
    );
  }

  ngOnDestroy() {
    for (const x of this.subscriptions) {
      x.unsubscribe();
    }
  }
}

ske
  • 4,694
  • 3
  • 23
  • 35
  • Your thought is apparently different from the others. But thanks for the link. I have been reading that article but I don't think it particularly talks about the scenario in question. BTW, I think you can just add all those subscriptions to one parent and unsubscribe from the parent, instead of an unsubscribing loop. – Antediluvian Oct 18 '19 at 04:00