We all know we need to clear (unsubscribe) our subscriptions when ever component will be destroyed.
Let's see how we can use Subscription
class from RxJs
to do this. π₯
Let's look at our component:
import {Component, OnInit} from "@angular/core";
import { Observable } from 'rxjs';
@Component({
selector: 'app-componento',
template: `<div>Component</div>`
})
export class Componento implements OnInit {
obs: Observable<any> = new Observable;
ngOnInit(): void {
this.obs.subscribe(() => {});
}
}
Good, now let's how we can use subscription to unsubscribe on destroy
import {Component, OnDestroy, OnInit} from "@angular/core";
import { Observable, Subscription } from 'rxjs';
@Component({
selector: 'app-componento',
template: `<div>Component</div>`
})
export class Componento implements OnInit, OnDestroy {
obs: Observable<any> = new Observable;
subs: Subscription = new Subscription;
ngOnInit(): void {
this.subs.add(this.obs.subscribe(() => {}));
}
ngOnDestroy(): void {
this.subs.unsubscribe();
}
}
That's it !
More readable version in case of having multiple observable, will be like this:
import {Component, OnDestroy, OnInit} from "@angular/core";
import { Observable, Subscription } from 'rxjs';
@Component({
selector: 'app-componento',
template: `<div>Component</div>`
})
export class Componento implements OnInit, OnDestroy {
obs: Observable<any> = new Observable;
obs2: Observable<any> = new Observable;
obs3: Observable<any> = new Observable;
subs: Subscription = new Subscription;
ngOnInit(): void {
this.subToOb();
this.subToOb2();
this.subToOb3();
}
ngOnDestroy(): void {
this.subs.unsubscribe();
}
private subToOb(): void {
this.subs.add(this.obs.subscribe(() => {}));
}
private subToOb2(): void {
this.subs.add(this.obs2.subscribe(() => {}));
}
private subToOb3(): void {
this.subs.add(this.obs3.subscribe(() => {}));
}
}
Have a good day π»
Top comments (0)