Skip to content

Instantly share code, notes, and snippets.

@juanmendes
Last active October 18, 2019 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanmendes/14567ec3afdf69e78e2cdb422f05bce2 to your computer and use it in GitHub Desktop.
Save juanmendes/14567ec3afdf69e78e2cdb422f05bce2 to your computer and use it in GitHub Desktop.
Unsubscribes automatically when component is destroyed.
export class SubscriptionTracker {
private subscriptions: Subscription[] = [];
constructor(destroyable: OnDestroy) {
const originalOnDestroy = destroyable.ngOnDestroy;
destroyable.ngOnDestroy = () => {
this.unsubscribeAll();
originalOnDestroy.call(destroyable);
};
}
subscribe<T>(
observable: Observable<T>,
observerOrNext?: PartialObserver<T> | ((value: T) => void),
error?: (error: any) => void,
complete?: () => void
): Subscription {
const subscription = observable.subscribe(
toSubscriber(observerOrNext, error, complete)
);
this.subscriptions.push(subscription);
return subscription;
}
unsubscribe(subscription: Subscription) {
subscription.unsubscribe();
const indexOfSubscription = this.subscriptions.indexOf(subscription);
if (indexOfSubscription == -1) {
throw new Error("Unsubscribing to untracked subscription");
}
this.subscriptions.splice(indexOfSubscription, 1);
return subscription;
}
unsubscribeAll() {
this.subscriptions.forEach((subscription) => subscription.unsubscribe());
this.subscriptions = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment