Week 06 · Day 04 — RxJS Operators:map / filter / switchMap / debounceTime
學習目標
- 理解 operators 如何轉換串流
- 掌握
map/filter - 掌握
switchMap/mergeMap/debounceTime
重點
operators 是串流的加工廠
- 放在 .pipe(...) 中
- map 轉換值、filter 篩選值
map / filter
import { of } from 'rxjs';
import { filter, map } from 'rxjs/operators';
of(1, 2, 3, 4, 5).pipe(
filter(n => n % 2 === 0), // 留偶數:2,4
map(n => n * 10) // 轉換 → 20,40
).subscribe(r => console.log(r));
switchMap:切換串流(常用於搜尋) - 當新事件來臨,取消前一個串流的訂閱 - 適合搜尋(避免舊結果覆蓋新結果)
import { switchMap, debounceTime, map } from 'rxjs/operators';
import { fromEvent } from 'rxjs';
const searchInput = document.getElementById('search');
fromEvent(searchInput, 'input').pipe(
debounceTime(300), // 停止輸入 300ms 才觸發
map((e: any) => e.target.value),
switchMap(query => this.searchService.search(query)) // 換成新的搜尋串流
).subscribe(results => {
this.results = results;
});
mergeMap 對比
- switchMap:只保留最新(取消舊的)
- mergeMap:並行保留所有訂閱(不取消)
實作
- 用
filter+map篩選並轉換一組數字 - 用
fromEvent+debounceTime+switchMap做搜尋 - 比較 switchMap 與 mergeMap 行為差別
作業
- 用
filter/map處理一串資料 - 用
debounceTime延遲觸發 - 說明
switchMap的用途與特色