Created
October 7, 2019 11:52
-
-
Save mohamedelshorbagy/2d9695261a2d8bc2e55b800eb010af57 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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; | |
}; | |
} |
This file contains hidden or 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 { 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