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
@Component({}) | |
class NonLeakyComponent extends SubscriptionTrackerMixin(Object) implements OnDestroy { | |
ngOnInit() { | |
const myTimer = timer(1,1); | |
this.subscribe(myTimer, () => console.log("timer 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
type Constructor<T = {}> = new (...args: any[]) => T; | |
function SubscriptionTrackerMixin<TBase extends Constructor>(Base: TBase) { | |
return class extends Base implements OnDestroy { | |
private subscriptions: Subscription[] = []; | |
public subscribe<T>( | |
observable: Observable<T>, | |
observerOrNext?: PartialObserver<T> | ((value: T) => void), |
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
@Component({}) | |
class NotLeakyComponent implements OnDestroy { | |
private subTracker: SubscriptionTracker; | |
ngOnInit() { | |
const myTimer = timer(1,1); | |
this.subTracker.subscribe(myTimer, | |
() => console.log("timer 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
export class SubscriptionTracker { | |
private subscriptions: Subscription[] = []; | |
constructor(destroyable: OnDestroy) { | |
const originalOnDestroy = destroyable.ngOnDestroy; | |
destroyable.ngOnDestroy = () => { | |
this.unsubscribeAll(); | |
originalOnDestroy.call(destroyable); | |
}; | |
} |
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
@Component({}) | |
class NonLeakyComponent implements OnDestroy { | |
private subscriptions: Subscription[]; | |
ngOnInit() { | |
const myTimer = timer(1,1); | |
this.subscriptions.push(myTimer.subscribe( | |
() => console.log("timer called") | |
)); |