Skip to content

Instantly share code, notes, and snippets.

@cedrickring
Last active February 5, 2019 21:24
Show Gist options
  • Save cedrickring/2770b2b6db9586e66eac35c3dea912a8 to your computer and use it in GitHub Desktop.
Save cedrickring/2770b2b6db9586e66eac35c3dea912a8 to your computer and use it in GitHub Desktop.
Add this to decorator to your RxJS Subscription's to unsubscribe them when ngOnDestroy is called
import { Subscription } from 'rxjs';
/**
* Example:
*
* ```
* @Unsubscribe()
* public subscription: Subscription
* ```
*
* or if you want another method to be called, use
*
* ```
* @Unsubscribe('myCustomMethod')
* public subscription: Subscription
* ```
*/
export function Unsubscribe(on: string = 'ngOnDestroy'): PropertyDecorator {
return function (target: Object, propertyKey: string | symbol) {
const oldFunction: Function = target[on];
replaceFunction(target, on, function () {
if (oldFunction) {
oldFunction.apply(this);
}
if (checkForSubscription(this[propertyKey])) {
this[propertyKey].unsubscribe();
}
});
};
}
function replaceFunction(target: any, name: string, newFunction: Function): void {
Object.defineProperty(target, name, {
value: newFunction
});
}
function checkForSubscription(property: any): boolean {
return property && property instanceof Subscription;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment