天天看點

通過rxjs的一個例子, 來學習SwitchMap的使用方法

switchMap相關文章

rxjs裡switchMap operators的用法

通過rxjs的一個例子, 來學習SwitchMap的使用方法

rxjs switchMap的實作原理

rxjs的map和switchMap在SAP Spartacus中的應用 -将高階Observable進行flatten操作

源代碼:

import { Observable, of, OperatorFunction } from "rxjs";

import { map } from "rxjs/operators";

import { interval } from "rxjs";

import { switchMap } from "rxjs/operators";

/* Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.

switchMap将source value映射成一個新的Observable,這個Observable被output Observable自動merge.

隻會從最新的被projected過後的Observable裡emit資料

給consumer

*/

const add100 = (counter: number) => {

 return of(counter + 100);

};

const addFunctionOperator: OperatorFunction = switchMap(add100);

const pollTasks = () => {

 return interval(1000).pipe(addFunctionOperator);

// caller can do subscription and store it as a handle:

let tasksSubscription = pollTasks().subscribe(data =>

 console.log("timestamp: " + new Date() + ": " + data)

);

// turn it off at a later time

setTimeout(() => tasksSubscription.unsubscribe(), 3000);

通過rxjs的一個例子, 來學習SwitchMap的使用方法

繼續閱讀