I just watched a ngConf video of John Papa talking about SubSink as a best practice in order to unsubscribe from obversables.
I was actually using Subscriptions[] then push subscriptions into it then forEach unsubscribe at cmp destroy.
Is their something I missed or is it just a readability improvment to use SubSink ?
Another way, without installing third party libraries is to group subscriptions up with .add() method
export class CustomerComponent implements OnInit, OnDestroy {
constructor(
private dataService: DataService
){}
private subs = new Subscription();
ngOnInit() {
this.subs.add(this.dataService.getCustomer().subscribe());
this.subs.add(this.dataService.getProducts().subscribe());
}
ngOnDestroy() {
this.subs.unsubscribe();
}
}
Adopting this way has at least one benefit - you move this code outside of your application logic. Because unsubscribing is just a clean up (a must). It is not related with the logic you create in your app.
And moving one step further, you can omit ngOnDestroy
from components and create one adapter with NgOnDestroy
implemented and place all logic there.
import { OnDestroy } from '@angular/core';
import { SubSink } from './sub-sink';
/**
* A class that automatically unsubscribes all observables when
* the object gets destroyed
*/
export class UnsubscribeOnDestroyAdapter implements OnDestroy {
/**The subscription sink object that stores all subscriptions */
subs = new SubSink();
/**
* The lifecycle hook that unsubscribes all subscriptions
* when the component / object gets destroyed
*/
ngOnDestroy(): void {
this.subs.unsubscribe();
}
How to automatically unsubscribe your RxJs observables
Other than that, it is a very tiny package, only few lines of code. Thanks for sharing :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With