common-ui/src/lib/utils/auto-unsubscribe.directive.ts
2022-01-13 00:19:52 +02:00

48 lines
1.6 KiB
TypeScript

import { Directive, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { OnDetach } from './custom-route-reuse.strategy';
/**
* Inherit this class when you need to subscribe to observables in your components
*/
@Directive()
export abstract class AutoUnsubscribe implements OnDestroy, OnDetach {
private readonly _subscriptions = new Subscription();
private readonly _activeScreenSubscriptions = 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);
}
/**
* Call this method when you want to subscribe to an observable while the screen is active
* @param subscription - the new subscription to add to subscriptions array
*/
set addActiveScreenSubscription(subscription: Subscription) {
this._activeScreenSubscriptions.closed = false;
this._activeScreenSubscriptions.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.ngOnDetach();
this._subscriptions.unsubscribe();
}
/**
* This method unsubscribes active subscriptions for active screens
*/
ngOnDetach(): void {
this._activeScreenSubscriptions.unsubscribe();
}
}