Skip to content

Instantly share code, notes, and snippets.

@pedrualves
Forked from belchior/unsubscribe-good-pratices.md
Last active October 9, 2018 18:42
Show Gist options
  • Save pedrualves/5320d529aeac730bc52fa084392ab271 to your computer and use it in GitHub Desktop.
Save pedrualves/5320d529aeac730bc52fa084392ab271 to your computer and use it in GitHub Desktop.
Boas práticas para unsubscribe

Boas práticas para unsubscribe

Unsubscribe é um tema importante que deve ser pensando quando são desenvolvidas aplicações grandes e escaláveis. Sua utilização é larga em projetos Angular e existe diversas abordagens para lidar com os Observables abaixo está listada as mais populares e consolidadas pela comunidade.

Nota 1: Alguns autores[7][8] advogam que não é necessário desligar Observables criados pelo HttpClient dado que esta tarefa é feita automaticamente pelo Angular, entretanto não é explicado como e não possuem referencias oficiais e até a data da confecção deste material não há um posicionamento oficial do time do Angular sobre o assunto.

Nota 2 Considerando que desligar Observables não compromete a estabilidade ou a performance de aplicações Angular o que predomina é a boa prática do rxjs de desligar os Observables.

Desligando Observables com first

// ...
import { first } from 'rxjs/operators';
// ...
export class MyComponent {
    ngOnInit() {
        this.service.method().pipe(first()).subscribe(props => this.props = props);
    }
}
// ...

Desligando Observables com takeWhile

// ...
import { takeWhile } from 'rxjs/operators';
// ...
export class MyComponent {
    private alive = true;

    ngOnInit() {
        const predicate = () => this.alive;
        this.service.method().pipe(takeWhile(predicate)).subscribe(props => this.props = props);
    }

    ngOnDestroy() {
        this.alive = false;
    }
}
// ...

Desligando Observables com takeUntil

// ...
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
// ...
export class MyComponent {
    private unsubscribe = new Subject();

    ngOnInit() {
        this.service.method().pipe(takeUntil(unsubscribe)).subscribe(props => this.props = props);
    }

    ngOnDestroy() {
        this.unsubscribe.next();
    }
}
// ...

Desligando Observables com unsubscribe

// ...
export class MyComponent {
    private subscriptions = [];

    ngOnInit() {
        const sub1 = this.service.method1().subscribe(props => this.props = props);
        const sub2 = this.service.method2().subscribe(props => this.props = props);

        this.subscriptions.push(sub1, sub2);
    }

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

Hipóteses a serem validadas

  • HttpClient é capaz de manter conexões: WebSocket, UDP, Event Stream? Show me the code

Referencia

RxJS

[1] first - https://rxjs-dev.firebaseapp.com/api/operators/first

[2] takeWhile - https://rxjs-dev.firebaseapp.com/api/operators/takeWhile

[3] takeUntil - https://rxjs-dev.firebaseapp.com/api/operators/takeUntil

[4] Subscription - https://rxjs-dev.firebaseapp.com/api/index/class/Subscription

[5] Angular: Don't forget to unsubscribe() - https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/

[6] RxJS: Don’t Unsubscribe - https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

[7] When to Unsubscribe in Angular - https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3

[8] Remember to unsubscribe() from streams in your Angular components- https://medium.com/@maciekprzybylski/remember-to-unsubscribe-from-streams-in-your-angular-components-caf0bedd6ac2

[9] RxJS: Avoiding takeUntil Leaks - https://blog.angularindepth.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef

[10] Why It’s Important to Unsubscribe from RxJS Subscription - https://netbasal.com/why-its-important-to-unsubscribe-from-rxjs-subscription-a7a6455d6a02

[11] Podcast: RxJS with Ben Lesh, Tracy Lee, and Jay Phelps - https://devchat.tv/adv-in-angular/aia-199-rxjs-with-ben-lesh-tracy-lee-and-jay-phelps/

[12] Angular/RxJS When should I unsubscribe from Subscription - https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163#41177163

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment