Created
July 1, 2018 09:58
-
-
Save ahmadarif/5146a679d6cdbc9dbb237988870b8ae1 to your computer and use it in GitHub Desktop.
Decorator for unsubscribe Subscriber
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 { Subscriber } from "rxjs"; | |
/** | |
* @example | |
* | |
* @Component({}) | |
* @DestroySubscribers() | |
* export class YourComponent { | |
* createSub: Subscription = new Subscription(); | |
* subscribers: Subscription[] = []; | |
* | |
* ownMethod() { | |
* // some code subscribe | |
* this.createSub = blablabla.subscribe( | |
* res => console.log(res) | |
* ); | |
* this.subscribers.push(this.createSub); | |
* } | |
* } | |
*/ | |
export default function DestroySubscribers() { | |
return function (target: any) { | |
// decorating the function ngOnDestroy | |
target.prototype.ngOnDestroy = ngOnDestroyDecorator(target.prototype.ngOnDestroy); | |
function ngOnDestroyDecorator(f) { | |
return function () { | |
let superData = f ? f.apply(this, arguments) : null; | |
// unsubscribing | |
for (let subscriberKey in this.subscribers) { | |
let subscriber = this.subscribers[subscriberKey]; | |
if (subscriber instanceof Subscriber) { | |
subscriber.unsubscribe(); | |
} | |
} | |
// returning the result of ngOnDestroy performance | |
return superData; | |
} | |
} | |
// returning the decorated class | |
return target; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment