2

I have a component that act as a sub-component of a big container component that orchestrates a slightly bigger form (using Reactive Forms)

I have this piece of code:

ngOnInit() {
    this.subscriptions.push(this.form.get('total').valueChanges.subscribe(data => {
      this.cdr.markForCheck();
    }));
  }

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}

Question: is this required? Even if the component is destroyed alongside the form?

Luke1988
  • 1,850
  • 2
  • 24
  • 42
  • Unsubscribing in `ngOnDestroy` is not always strictly necessary but is a good practice. Why it is not always necessary? Because there are cases where Observables `complete` by themselves, e.g. with `http` client. Destroying a component does not equate to unsubscribing its subscriptions. This is why it is a good practice to unsubscribe, to avoid keeping subscriptions hanging around the app. – Picci Apr 10 '20 at 08:30
  • I think you have your answer here: https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription – Terry Apr 10 '20 at 08:32
  • I think this answer might help, have a look at this: https://stackoverflow.com/a/57009988/8578281 – Goga Koreli Apr 14 '20 at 23:03

1 Answers1

0

if its a sequence that completes (like an http request) the manual cleanup is unnecessary (assuming you subscribe in the controller manually).

if its an infinite sequence, like this one, you should unsubscribe from it.

It's considered a good practice to unsubscribe from all the observables just in case.

I use subsink for this. John Papa was talking about this in a video and recommending this lib.

jeprubio
  • 17,312
  • 5
  • 45
  • 56