Skip to content

Instantly share code, notes, and snippets.

View juanmendes's full-sized avatar

Ruan Mendes juanmendes

View GitHub Profile
@juanmendes
juanmendes / non-leaky.component.ts
Created October 18, 2019 14:54
Simple unsubscribing
@Component({})
class NonLeakyComponent implements OnDestroy {
private subscriptions: Subscription[];
ngOnInit() {
const myTimer = timer(1,1);
this.subscriptions.push(myTimer.subscribe(
() => console.log("timer called")
));
@juanmendes
juanmendes / subscription-tracker.ts
Last active October 18, 2019 14:56
Unsubscribes automatically when component is destroyed.
export class SubscriptionTracker {
private subscriptions: Subscription[] = [];
constructor(destroyable: OnDestroy) {
const originalOnDestroy = destroyable.ngOnDestroy;
destroyable.ngOnDestroy = () => {
this.unsubscribeAll();
originalOnDestroy.call(destroyable);
};
}
@Component({})
class NotLeakyComponent implements OnDestroy {
private subTracker: SubscriptionTracker;
ngOnInit() {
const myTimer = timer(1,1);
this.subTracker.subscribe(myTimer,
() => console.log("timer called")
);
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),
@juanmendes
juanmendes / component-with=tracker-mixin.ts
Last active March 25, 2020 19:58
A component that uses the SubscriptionTrackerMixin
@Component({})
class NonLeakyComponent extends SubscriptionTrackerMixin(Object) implements OnDestroy {
ngOnInit() {
const myTimer = timer(1,1);
this.subscribe(myTimer, () => console.log("timer called"));
}
}