Performance: Why observables matter in Angular
Observables affect how Angular handles asynchronous data streams, impacting interaction responsiveness and rendering updates.
items$ = this.dataService.getData(); // use async pipe in template
this.dataService.getData().subscribe(data => { this.items = data; });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct subscribe in component | Multiple DOM updates per emission | Multiple reflows per update | High paint cost due to frequent updates | [X] Bad |
| Async pipe with observable | Minimal DOM updates only on new data | Single reflow per update | Lower paint cost with efficient updates | [OK] Good |
subscribe.subscribe. Others like listen, on, and watch are not valid observable methods.const obs = new Observable(subscriber => {
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
subscriber.next(3);
});
obs.subscribe(value => console.log(value));complete(). After completion, emissions stop, so 3 is ignored.this.data$ = this.http.get('/api/data');
this.data$.subscribe(data => {
this.data = data;
});
this.data$.subscribe(data => {
console.log(data);
});this.data$ is subscribed twice, so two HTTP requests are sent, which is inefficient and often unwanted.interval observable emits values at set intervals, perfect for updating time every second.ngOnInit and unsubscribing on destroy prevents memory leaks and keeps updates smooth.interval(1000).subscribe(time => this.currentTime = new Date()) inside ngOnInit and unsubscribe on destroy. -> Option APass the test and this pattern moves unknown