Week 09 · Day 06 — async pipe 與訂閱管理對比

學習目標

  • 確認 async pipe 自動管理訂閱
  • 比較 async / takeUntil / unsubscribe
  • 養成「最少記憶體殘留」的習慣

重點

async pipe 自動化

@Component({
  template: `
    <div *ngIf="data$ | async as data">
      {{ data.name }}
    </div>
  `
})
export class AsyncComponent {
  data$ = this.dataService.getData();
}
- data$ | async:自動訂閱、自動退訂 - 配 *ngIf ... as:在模板中當區域變數使用 - 元件銷毀時 pipe 自動退訂,零手動清理

三種訂閱管理對比 | 方式 | 清理方式 | 適合 | |------|----------|------| | 模板 async pipe | 自動 | 大部分顯示用途,推薦 | | 類別 subscribe + takeUntil | 在 ngOnDestroy 觸發 destroy$ | 需要在類別內處理值 | | 直接 unsubscribe() | 手動呼叫 | 單一訂閱變數情境 |

takeUntil 的類別版

export class Component {
  private destroy$ = new Subject<void>();

  ngOnInit(): void {
    this.service.data$
      .pipe(takeUntil(this.destroy$))
      .subscribe(v => this.value = v);
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

記憶體管理原則 - 能使用 async pipe 就用 async - 需在類別取值的訂閱,一律 takeUntil - 避免手動 subscribe 卻遺忘退訂

實作

  1. 把 Day05 的類別版改用 async pipe
  2. 對比 template 與 class 兩種寫法成效
  3. 用 Chrome DevTools Memory 觀察切換前後有無洩漏

作業

  • 用 async pipe 完成自動訂閱
  • 比較 async / takeUntil / unsubscribe
  • 複習並套用「最少洩漏」原則