Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular: Unsubscribe prop subscriptions #12514

Merged
merged 1 commit into from Sep 24, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -33,6 +33,8 @@ export class AppComponent implements OnInit, OnDestroy {

subscription: Subscription;

propSubscriptions = new Map<any, { prop: any, sub: Subscription }>();

constructor(
private cfr: ComponentFactoryResolver,
private changeDetectorRef: ChangeDetectorRef,
Expand Down Expand Up @@ -64,6 +66,13 @@ export class AppComponent implements OnInit, OnDestroy {
if (this.subscription) {
this.subscription.unsubscribe();
}

this.propSubscriptions.forEach(v => {
if (!v.sub.closed) {
v.sub.unsubscribe();
}
})
this.propSubscriptions.clear();
}

/**
Expand Down Expand Up @@ -93,7 +102,7 @@ export class AppComponent implements OnInit, OnDestroy {
}
}
} else if (typeof value === 'function' && key !== 'ngModelChange') {
instanceProperty.subscribe(value);
this.setPropSubscription(key, instanceProperty, value);
}
});

Expand Down Expand Up @@ -123,4 +132,26 @@ export class AppComponent implements OnInit, OnDestroy {
instance.registerOnChange(props.ngModelChange);
}
}

/**
* Store ref to subscription for cleanup in 'ngOnDestroy' and check if
* observable needs to be resubscribed to, before creating a new subscription.
*/
private setPropSubscription(key: string, instanceProperty: Observable<any>, value: any): void {
if (this.propSubscriptions.has(key)) {
const v = this.propSubscriptions.get(key);
if (v.prop === value) {
// Prop hasn't changed, so the existing subscription can stay.
return;
}

// Now that the value has changed, unsubscribe from the previous value's subscription.
if (!v.sub.closed) {
v.sub.unsubscribe();
}
}

const sub = instanceProperty.subscribe(value);
this.propSubscriptions.set(key, { prop: value, sub });
}
}