Last active
February 5, 2019 21:24
-
-
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
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
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