common-ui/src/lib/utils/auto-unsubscribe.directive.ts
2024-06-19 13:05:12 +03:00

49 lines
1.6 KiB
TypeScript

import { Directive, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { OnDetach } from './custom-route-reuse.strategy';
/**
* @deprecated Use takeUntilDestroyed()
* TODO: remove this asap
*/
@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();
}
}