Performance: BehaviorSubject as simple store
MEDIUM IMPACT
This affects interaction responsiveness and rendering updates by controlling how often Angular components re-render based on store changes.
import { BehaviorSubject } from 'rxjs'; import { distinctUntilChanged, map } from 'rxjs/operators'; const store = new BehaviorSubject({ count: 0 }); // In component store.pipe( map(state => state.count), distinctUntilChanged() ).subscribe(count => { this.count = count; }); // Updating store frequently store.next({ count: Math.random() });
import { BehaviorSubject } from 'rxjs'; const store = new BehaviorSubject({ count: 0 }); // In component store.subscribe(value => { // Directly update component state on every emission this.count = value.count; // No filtering or distinct checks }); // Updating store frequently store.next({ count: Math.random() });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| BehaviorSubject without filtering | Many updates to component state | Multiple reflows due to frequent DOM updates | High paint cost from unnecessary renders | [X] Bad |
| BehaviorSubject with distinctUntilChanged | Updates only on meaningful state changes | Single or minimal reflows | Lower paint cost due to fewer renders | [OK] Good |