Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

381
Visualizações
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. I do not need to do that for finite Observables as they will complete 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 with the component that contains it, so I think that they will be no memory leak 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 do not unsubscribe from this.form.valueChanges; when my component is destroyed, the this.form.valueChanges will be destroyed too.

Will there be a memory leak in this case?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

As Babar had mention, you need to do the unsubscribe in order to stop those subscriptions to continue watching for changes.

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.

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(): void {
  this.subscriptions.forEach((elem) => { elem.unsubscribe(); })
}
about 4 years ago · Santiago Trujillo Relatório

0

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();
 }
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda