Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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