From 29995f481c2d353df4ab648a4132f45dea012df1 Mon Sep 17 00:00:00 2001 From: Dan Percic Date: Thu, 29 Jul 2021 13:19:01 +0300 Subject: [PATCH] add auto unsubscribe component --- src/index.ts | 1 + src/lib/base/auto-unsubscribe.component.ts | 28 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 src/lib/base/auto-unsubscribe.component.ts diff --git a/src/index.ts b/src/index.ts index e92fee3..b2e3142 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ export * from './lib/common-ui.module'; export * from './lib/buttons/icon-button/icon-button.component'; export * from './lib/buttons/icon-button/icon-button-type.model'; +export * from './lib/base/auto-unsubscribe.component'; diff --git a/src/lib/base/auto-unsubscribe.component.ts b/src/lib/base/auto-unsubscribe.component.ts new file mode 100644 index 0000000..2fab40a --- /dev/null +++ b/src/lib/base/auto-unsubscribe.component.ts @@ -0,0 +1,28 @@ +import { Component, OnDestroy } from '@angular/core'; +import { Subscription } from 'rxjs'; + +/** + * Inherit this class when you need to subscribe to observables in your components + */ +@Component({ template: '' }) +export abstract class AutoUnsubscribeComponent 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(); + } +}