rxjs里switchMap operators的用法
生活随笔
收集整理的這篇文章主要介紹了
rxjs里switchMap operators的用法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
switchMap相關(guān)文章
- rxjs里switchMap operators的用法
- 通過(guò)rxjs的一個(gè)例子, 來(lái)學(xué)習(xí)SwitchMap的使用方法
- rxjs switchMap的實(shí)現(xiàn)原理
- rxjs的map和switchMap在SAP Spartacus中的應(yīng)用 -將高階Observable進(jìn)行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的輸出是一個(gè)新的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是一個(gè)函數(shù),接受一個(gè)number輸入,返回一個(gè)Observable對(duì)象,包含3個(gè)number元素const fn = (x: number) => of(x, x ** 2, x ** 3);// OperatorFunction:尖括號(hào)里前一個(gè)number是輸入類(lèi)型// 第二個(gè)括號(hào)是輸出類(lèi)型const mapper: OperatorFunction<number, number> = switchMap(fn);// pipe需要接受的類(lèi)型是OperatorFunction,經(jīng)過(guò)operator傳入一個(gè)// funcion進(jìn)去組合而成const switched = origin.pipe(mapper);switched.subscribe(x => console.log('diablo: ' + x));總結(jié):OperatorFunction的類(lèi)型很形象,由Operator接收一個(gè)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);// 需要傳一個(gè)Observable進(jìn)去const mapper = switchMapTo(int);const switched = origin.pipe(mapper);switched.subscribe(x => console.log('diablo2: ' + x));測(cè)試結(jié)果:origin里的value完全沒(méi)有被考慮:
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的rxjs里switchMap operators的用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 黑犀牛坐飞机,为什么要四脚朝天、倒吊着,
- 下一篇: 期货交易入门知识 期货的含义