TakeUntilDestroy is a decorator for Angular that handles unsubscriptions on component destroy. If you have subscriptions that exist till the component destroy, just define a function or property that returns or is an observable and use this decorator. No triggers, no subscriptions, no 'ngOnDestroy' with just unsubscription purpose.
ng-rxjs-take-until-destroy
A decorator that automatically unsubscribes observables returned by decorated values on Angular component's 'ngOnDestroy' call.
Installation
npm i ng-rxjs-take-until-destroy
Usage
implements OnInit @TakeUntilDestroy obs$: BehaviorSubject<number> = 5; { } { this; this; } @TakeUntilDestroy private : Observable<StreamAType> return thisserviceA; @TakeUntilDestroy private : Observable<StreamBType> return thisserviceB;
What's going on under the hood?
The decorator...
- Adds once a trigger which is a Subject.
- Modified decorated function or property calling rxjs' 'takeUntil' function on returned value.
- Adds 'ngOnDestroy' function to the component or extends already existing.
- Performs 'next' and 'complete' on earlier added trigger on 'ngOnDestroy' call.
in fact the above component without 'TakeUntilDestroy' decorator would be looking like
implements OnInit OnDestroy obs$: BehaviorSubject<number> = 5; private trigger: Subject<any> = ; { } { thisobs$ ; this ; this ; } { thistriggernext; thistriggercomplete; }
Important
Using Angular CLI with AOT compilation, the ngOnDestroy method has to be implemented directly to component (even if it means to make an empty method). Otherwise TakeUntilDestroy
decorator won't be able to create it and modify itself.
implements OnInit { } { this; this; } {} @TakeUntilDestroy private : Observable<StreamAType> return thisserviceA;