Performance: Subscribing to observables
This affects interaction responsiveness and memory usage by controlling how data streams update the UI and how resources are managed.
private subscription = this.dataService.getData().subscribe(data => { this.items = data; }); ngOnDestroy() { this.subscription.unsubscribe(); }
this.dataService.getData().subscribe(data => { this.items = data; });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual subscribe without unsubscribe | Multiple updates even after component destroyed | Multiple reflows due to repeated change detection | High paint cost from unnecessary UI updates | [X] Bad |
| Manual subscribe with unsubscribe in ngOnDestroy | Updates only while component alive | Single reflow per update cycle | Moderate paint cost | [!] OK |
| Using async pipe in template | Updates only when data changes and auto cleans up | Minimal reflows | Low paint cost | [OK] Good |
data$ in Angular?data$.subscribe with an arrow function receiving the emitted value.const obs$ = of(1, 2, 3);
obs$.subscribe({
next: x => console.log(x),
error: err => console.error(err),
complete: () => console.log('Done')
});next callback logs each value, then complete logs 'Done'.this.data$.subscribe(data => {
this.value = data;
});
// No unsubscribe called anywhereobs1$ and obs2$ and combine their latest values whenever either emits. Which RxJS operator should you use before subscribing?combineLatest emits an array of latest values from all observables whenever any emits.Pass the test and this pattern moves unknown