rxjs里switchMap operators的用法
生活随笔
收集整理的這篇文章主要介紹了
rxjs里switchMap operators的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
switchMap相關文章
- rxjs里switchMap operators的用法
- 通過rxjs的一個例子, 來學習SwitchMap的使用方法
- rxjs switchMap的實現原理
- rxjs的map和switchMap在SAP Spartacus中的應用 -將高階Observable進行flatten操作
Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.
理解記憶法:switchMap -> switch to a new Observable,亦即SwitchMap返回的OperatorFunction,其function的輸出是一個新的Observable.
例子:
const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));switched.subscribe(x => console.log(x));輸出:
/*const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));switched.subscribe(x => console.log(x));*/const origin = of(1, 2, 3);// fn是一個函數,接受一個number輸入,返回一個Observable對象,包含3個number元素const fn = (x: number) => of(x, x ** 2, x ** 3);// OperatorFunction:尖括號里前一個number是輸入類型// 第二個括號是輸出類型const mapper: OperatorFunction<number, number> = switchMap(fn);// pipe需要接受的類型是OperatorFunction,經過operator傳入一個// funcion進去組合而成const switched = origin.pipe(mapper);switched.subscribe(x => console.log('diablo: ' + x));總結:OperatorFunction的類型很形象,由Operator接收一個function作為輸入,組裝而成
switchMapTo
const origin = of(111, 222, 333);const copy = origin.pipe(map( (x) => x + 1));// observable: ObservableInput<R>const int = interval(1000).pipe(take(3));const fn = (x: number) => of(x, x ** 2, x ** 3);// 需要傳一個Observable進去const mapper = switchMapTo(int);const switched = origin.pipe(mapper);switched.subscribe(x => console.log('diablo2: ' + x));測試結果:origin里的value完全沒有被考慮:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的rxjs里switchMap operators的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑犀牛坐飞机,为什么要四脚朝天、倒吊着,
- 下一篇: 期货交易入门知识 期货的含义