Skip to content

Instantly share code, notes, and snippets.

@mohamedelshorbagy
Created October 7, 2019 11:52
Show Gist options
  • Save mohamedelshorbagy/2d9695261a2d8bc2e55b800eb010af57 to your computer and use it in GitHub Desktop.
Save mohamedelshorbagy/2d9695261a2d8bc2e55b800eb010af57 to your computer and use it in GitHub Desktop.
export function autoUnsubscribe(subscriptions: string[] = []) {
return (componentType) => {
const orgFactory = componentType.ngComponentDef.factory;
componentType.ngComponentDef.factory = (...args) => {
const component = orgFactory(...args);
componentType.ngComponentDef.onDestroy = () => {
if (component.ngOnDestroy) {
component.ngOnDestroy();
}
if (subscriptions && subscriptions.length) {
// Unsubscribe for specific subscriptions
subscriptions.forEach(key => {
if (component[key] && component[key].unsubscribe) {
console.log([key, component[key]])
component[key].unsubscribe();
}
})
} else {
// Unsubscribe for all keys
Object.keys(component)
.forEach(key => {
if (component[key] && component[key].unsubscribe) {
console.log([key, component[key]])
component[key].unsubscribe();
}
});
}
};
return component;
};
return componentType;
};
}
import { Component, OnInit } from '@angular/core';
import { Subscription, timer } from 'rxjs';
import { tap } from 'rxjs/operators';
import { autoUnsubscribe } from '../../unsubscribe';
// @autoUnsubscribe(['timerSubscription'])
@autoUnsubscribe()
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class homeComponent implements OnInit {
timerSubscription: Subscription;
constructor() { }
ngOnInit() {
this.timerSubscription = timer(0, 1000)
.pipe(
tap(console.log),
)
.subscribe(
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment