简体   繁体   English

Angular 2 / Rxjs:我真的需要取消订阅吗?

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

I understand that I must unsubscribe certains Observable (ie: Observables that have infinite value) when Components are destroyed in order to prevent memory leaks. 我知道我必须在销毁组件时取消订阅某些Observable(即:具有无限值的Observable)以防止内存泄漏。 I do not need to do that for finite Observables as they will complete and automatically unsubscribe . 对于有限的 Observables,我不需要这样做,因为它们将完成并自动unsubscribe

But if I create an infinite Observable in my component (for example FormGroup.valueChanges , or QueryList.changes ), this one will be destroyed with the component that contains it, so I think that they will be no memory leak even if I do not unsubscribe from it. 但是如果我在我的组件中创建一个无限的 Observable (例如FormGroup.valueChangesQueryList.changes ),那么这个将被包含它的组件销毁,所以我认为即使我不这样做也不会有内存泄漏取消订阅。

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 do not unsubscribe from this.form.valueChanges ; 在这里,我没有unsubscribe this.form.valueChanges ; when my component is destroyed, the this.form.valueChanges will be destroyed too. 当我的组件被销毁时, this.form.valueChanges也将被销毁。

Will there be a memory leak in this case? 在这种情况下是否会出现内存泄漏?

As Babar had mention, you need to do the unsubscribe in order to stop those subscriptions to continue watching for changes. 正如Babar所提到的,您需要进行取消订阅才能阻止这些订阅继续观看更改。

For your particular case I think that you have a point. 对于你的特殊情况,我认为你有一个观点。

One thing I do when I have a lot of subscriptions in the same component is the following. 当我在同一组件中有大量订阅时,我做的一件事如下。

First I create "subscriptions", an empty Array of Subscription type. 首先,我创建“订阅”,一个空的Subscription类型数组。

private subscriptions: Subscription[] = [];

Then every time I need to do subscribe I push it into the array 然后,每次我需要订阅时,我将它推入数组

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

And in the ngOnDestroy I unsubscribe to every subscription inside the array. 在ngOnDestroy中,我取消订阅数组中的每个订阅。

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

When your component is destroyed your subscribers are not they still waiting for any event came to them it will cost memory as well sometimes it may disturb your logics as well. 当您的组件被销毁时,您的订阅者不会等待任何事件发生在他们身上,这将花费内存,有时它也可能会打扰您的逻辑。 for example router events subscription it will trigger everywhere in your app and execute the code you did inside subscription. 例如,路由器事件订阅它将在您的应用程序中的任何位置触发,并执行您在订阅内执行的代码。

I second case if you switch between components and never unsubscribed your app will be hang up after a bunch of time because whenever you load the component new subscribers bind up. 我是第二种情况,如果您在组件之间切换并且从未取消订阅,您的应用程序将在一堆时间后挂断,因为无论何时加载组件,新订户都会绑定。

@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();
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM