Skip to content

Commit

Permalink
Merge pull request #12514 from Marklb/marklb/unsub-prop-subscriptions
Browse files Browse the repository at this point in the history
Angular: Unsubscribe prop subscriptions
  • Loading branch information
shilman committed Sep 26, 2020
1 parent 737cf05 commit 3790daf
Showing 1 changed file with 32 additions and 1 deletion.
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 });
}
}

0 comments on commit 3790daf

Please sign in to comment.