Last active
October 18, 2019 14:56
-
-
Save juanmendes/14567ec3afdf69e78e2cdb422f05bce2 to your computer and use it in GitHub Desktop.
Unsubscribes automatically when component is destroyed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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