Skip to content

Instantly share code, notes, and snippets.

@ahmadarif
Created July 1, 2018 09:58
Show Gist options
  • Save ahmadarif/5146a679d6cdbc9dbb237988870b8ae1 to your computer and use it in GitHub Desktop.
Save ahmadarif/5146a679d6cdbc9dbb237988870b8ae1 to your computer and use it in GitHub Desktop.
Decorator for unsubscribe Subscriber
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