Angular 2 / Rxjs: do I really need to unsubscribe?

I understand that I have to unsubscribe certains Observable (i.e. Observables that have infinite ) when components are destroyed to prevent memory leak. I do not need to do this for finite observables as they are completed and automatically unsubscribe .

But if I create an infinite Observable in my component (for example, FormGroup.valueChanges or QueryList.changes ), this one will be destroyed by the component that contains it, so I think that they will not leak memory, even if I do not unsubscribe from it.

Here is a simple example:

 @Component({}) export class DummyComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ firstName: [''], lastName: [''] }); this.form.valueChanges.subscribe( x => console.log(x) ); } } 

Here I am not unsubscribe from this.form.valueChanges ; when my component is destroyed, this.form.valueChanges will also be destroyed.

Will there be a memory leak in this case?

+6
source share
2 answers

As Babar said, you need to unsubscribe in order to stop the subscription in order to continue viewing the changes.

In your particular case, I think you have a point.

One thing I do when I have many subscribers in one component is the following.

First I create a “subscription”, an empty type “Subscription Type”.

 private subscriptions: Subscription[] = []; 

Then every time I need to subscribe, I insert it into an array

 this.subscriptions.push(this.form.valueChanges.subscribe(x => console.log(x))); 

And in ngOnDestroy, I unsubscribe from each subscription inside the array.

 ngOnDestroy(): void { this.subscriptions.forEach((elem) => { elem.unsubscribe(); }) } 
+4
source

When your component is destroyed, your subscribers do not expect any event to come to them, it will cost memory, and sometimes it can also break your logic. for example, subscribing to events in the router, it will run everywhere in your application and execute the code that you did inside the subscription.

In the second case, if you switch between components and never subscribe, your application will freeze after a few seconds, because whenever you download a component, new subscribers get attached.

 @Component({}) export class DummyComponent implements OnDestroy { form: FormGroup; subscription: Subscription; // from rxjs constructor(private fb: FormBuilder) { this.form = this.fb.group({ firstName: [''], lastName: [''] }); this.subscription = this.form.valueChanges.subscribe( x => console.log(x) ); } ngOnDestroy(): void { this.subscription.unsubscribe(); } } 
+2
source

Source: https://habr.com/ru/post/1015616/


All Articles