I've been conducting a little experiment related to handling state in an Angular component.
Let's say I have a variable costly to compute that depends on several others. I can write a function updateVar()
and call it on every event I know may impact it, eg. via subscriptions. But it doesn't feel very DRY nor robust when aforementioned function is called in more than 5 different places.
So instead, how about debouncing the DoCheck
Angular lifecycle hook ?
docheckSubject: Subject<any> = new Subject();
debounced: boolean = false;
constructor(private cd: ChangeDetectorRef) {}
ngOnInit() {
this.docheckSubject.debounceTime(50).subscribe(
() => this.ngDoCheckDebounced()
);
}
ngDoCheck() {
if (!this.debounced) {
this.docheckSubject.next();
} else {
this.debounced = false;
}
}
ngDoCheckDebounced() {
this.debounced = true;
this.updateVar();
this.cd.detectChanges(); // needed to reflect update in DOM
}
Here's a plunker example.
This approach seems to work fine in my real app, where of course way more ngDoCheck() are happening, and Protractor tests don't complain either. But I can't shake off the feeling of doing a dirty not-so-clever hack.
Question: Is this going to bite me ? In fact, do I need it at all ?