Performance: Subject types (Subject, BehaviorSubject, ReplaySubject)
This concept affects how efficiently Angular apps handle asynchronous data streams and UI updates, impacting interaction responsiveness and rendering smoothness.
const behaviorSubject = new BehaviorSubject(initialValue); behaviorSubject.subscribe(() => { // UI updates with latest cached value immediately }); behaviorSubject.next(value);
const subject = new Subject(); subject.subscribe(() => { // heavy UI update triggered on every emission }); subject.next(value);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Subject | Multiple subscriptions trigger repeated DOM updates | Multiple reflows if many emissions | High paint cost due to frequent UI changes | [X] Bad |
| BehaviorSubject | Single DOM update with cached latest value | Minimal reflows due to fewer emissions | Lower paint cost with controlled updates | [OK] Good |
| ReplaySubject | DOM updates with replayed values on subscription | Moderate reflows depending on buffer size | Moderate paint cost but consistent UI state | [!] OK |
const subject = new BehaviorSubject('start');
subject.next('first');
subject.subscribe(value => console.log('Subscriber 1:', value));
subject.next('second');
subject.subscribe(value => console.log('Subscriber 2:', value));const subject = new Subject();
subject.next('hello');
subject.subscribe(value => console.log(value));Pass the test and this pattern moves unknown