Created
October 18, 2019 14:59
-
-
Save juanmendes/bbbaa8ece5335f4c4c61862242df4eaf to your computer and use it in GitHub Desktop.
This file contains 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
type Constructor<T = {}> = new (...args: any[]) => T; | |
function SubscriptionTrackerMixin<TBase extends Constructor>(Base: TBase) { | |
return class extends Base implements OnDestroy { | |
private subscriptions: Subscription[] = []; | |
public 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; | |
} | |
public unsubscribe(subscription: Subscription) { | |
const indexOfSubscription = this.subscriptions.indexOf(subscription); | |
if (indexOfSubscription == -1) { | |
throw new Error("Unsubscribing to untracked subscription"); | |
} | |
subscription.unsubscribe(); | |
this.subscriptions.splice(indexOfSubscription, 1); | |
return subscription; | |
} | |
unsubscribeAll() { | |
this.subscriptions.forEach((subscription) => subscription.unsubscribe()); | |
this.subscriptions = []; | |
} | |
ngOnDestroy() { | |
this.unsubscribeAll(); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment