Performance: Observable vs Promise mental model
This concept affects how asynchronous data is handled, impacting interaction responsiveness and rendering updates in Angular apps.
fetchData(): Observable<Data> {
return this.http.get<Data>(url);
}
ngOnInit() {
this.fetchData().subscribe(data => {
this.data = data;
// UI updates reactively on each emission
});
}fetchData(): Promise<Data> { return this.http.get<Data>(url).toPromise(); } ngOnInit() { this.fetchData().then(data => { this.data = data; // No further updates possible }); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Promise (single resolution) | Single DOM update | 1 reflow | 1 paint | [OK] Good for single async data |
| Observable (multiple emissions) | Multiple DOM updates | Multiple reflows | Multiple paints | [!] OK if managed |
| Observable without throttling | Many DOM updates | Many reflows | High paint cost | [X] Bad if unthrottled |
Observable and a Promise in Angular?Promise represents a single future value or error that will be resolved once.Observable can emit multiple values over time and can be stopped or cancelled.Promise handles a single future value; Observable can handle multiple values over time. -> Option Bresolve and reject.resolve(42) inside the function correctly resolves the Promise with 42.const obs = new Observable(subscriber => {
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
obs.subscribe(value => console.log(value));const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 1000);
});
p.then(result => console.log(result));
p.catch(error => console.error(error));
p.cancel();p.cancel() will cause a runtime error because cancel() is undefined.Pass the test and this pattern moves unknown