Skip to content

Instantly share code, notes, and snippets.

@krishnathota
Last active June 22, 2021 02:02
Show Gist options
  • Save krishnathota/1477bb8d4cb72da31ee509d14dba5f56 to your computer and use it in GitHub Desktop.
Save krishnathota/1477bb8d4cb72da31ee509d14dba5f56 to your computer and use it in GitHub Desktop.
Use SubSink to Unsubscribe automatically
import { Injectable, OnDestroy } from '@angular/core';
import { SubscriptionLike } from 'rxjs';
import { SubSink } from 'subsink';
/**
* @description Keeps hold of your subscriptions and unsubscribes them when component is destroyed.
* This uses 'SubSink' library to achieve this.
* @usage Extend your component from this 'MyComponent extends Unsubscribe'. Call super() in your component's constructor.
* @important Please keep a note that if you happen to implement OnDestroy in your component,
* you have to explicitly call super.ngOnDestroy() to invoke un-subscription for the component.
* @param sub; Subscription list. Assign your subscriptions in your component to 'sub'
*/
@Injectable()
export abstract class Unsubscribe implements OnDestroy {
_subSink = new SubSink();
set sub(subscription: SubscriptionLike) {
this._subSink.sink = subscription;
}
ngOnDestroy(): void {
this._subSink.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment