common-ui/src/lib/utils/auto-unsubscribe.directive.ts
2021-08-16 21:19:47 +03:00

29 lines
924 B
TypeScript

import { Directive, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
/**
* Inherit this class when you need to subscribe to observables in your components
*/
@Directive()
export abstract class AutoUnsubscribe implements OnDestroy {
private readonly _subscriptions = new Subscription();
/**
* Call this method when you want to subscribe to an observable
* @param subscription - the new subscription to add to subscriptions array
*/
set addSubscription(subscription: Subscription) {
this._subscriptions.closed = false;
this._subscriptions.add(subscription);
}
/**
* This method unsubscribes active subscriptions
* If you implement OnDestroy in a component that inherits AutoUnsubscribeComponent,
* then you must explicitly call super.ngOnDestroy()
*/
ngOnDestroy(): void {
this._subscriptions.unsubscribe();
}
}