Week 06 · Day 03 — Observable(RxJS 基礎)

學習目標

  • 理解 Observable 與訂閱概念
  • 認識常見建立方式:of / from / interval
  • 掌握 subscribeunsubscribe

重點

Observable 是什麼 - 資料「可觀察的串流」:隨時間產生的多個值 - 需要 .subscribe() 才開始推送值 - 相較於 Promise(單次結果),Observable 可推多次

建立 Observable

import { Observable, of, from, interval } from 'rxjs';

of(1, 2, 3);                        // 依序推 1,2,3 後完成
from([10, 20]);                     // 從陣列產生串流
interval(1000);                     // 每秒推一個遞增數字

訂閱示例

const numbers$ = of(1, 2, 3);

numbers$.subscribe(result => console.log(result));
// 會依序印出 1, 2, 3

命名慣例 - 變數名加上 $ 表示是 Observable(如 numbers$

處理 HTTP 回傳 - http.get<T>() 回傳的就是 Observable - 換句話說,HttpClient 本身也是 RxJS 的一環

實作

import { of } from 'rxjs';

const nums$ = of(1, 2, 3, 4, 5);
nums$.subscribe(n => console.log('got', n));
再看:
import { interval } from 'rxjs';
const tick$ = interval(1000);
const sub = tick$.subscribe(t => console.log(t));
// 幾秒後
sub.unsubscribe();   // 停止

作業

  • of / from / interval 各建立 Observable
  • .subscribe() 接收值
  • 說出「為什麼要訂閱才會有值」