rxjs的一个例子:什么是rxjs的OperatorFunction?
生活随笔
收集整理的這篇文章主要介紹了
rxjs的一个例子:什么是rxjs的OperatorFunction?
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在StackBlitz里創(chuàng)建一個(gè)rxjs項(xiàng)目,源代碼如下:
import { Observable, of } from "rxjs"; import { map } from "rxjs/operators"; import { interval } from "rxjs"; import { switchMap } from "rxjs/operators";const pollTasks = () => {return interval(1000).pipe(switchMap(counter => {return of(counter + 100);}),map(res => res + res)); };// 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 timesetTimeout(() => tasksSubscription.unsubscribe(), 10000);十秒之后自動(dòng)關(guān)閉:
首先用rxjs interval創(chuàng)建一個(gè)Observable對(duì)象,每隔1秒鐘產(chǎn)生一個(gè)遞增的整數(shù):
interval(1000)返回的Observable調(diào)用pipe進(jìn)行下一步處理:switchMap.
注意該switchMap的類型,接受一個(gè)輸入?yún)?shù),project函數(shù)。該project函數(shù)的輸入是:value: number, index: number, 必須返回Observable. 整個(gè)project的函數(shù)類型是OperatorFunction<number, number>.
下面這個(gè)例子更加能夠說明問題:
import { Observable, of, OperatorFunction } from "rxjs"; import { map } from "rxjs/operators"; import { interval } from "rxjs"; import { switchMap } from "rxjs/operators";const add1Fn = value => value + 1; const add1OP: OperatorFunction<number, number> = map(add1Fn);const pollTasks = () => {return interval(1000).pipe(switchMap(counter => {return of(counter + 100);}),map(res => res + res),add1OP); };// 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 timesetTimeout(() => tasksSubscription.unsubscribe(), 3000);將函數(shù)傳入rxjs的operator,返回的是一個(gè)operatorFunction,將這個(gè)operatorFunction傳入pipe,返回的是新的Observable.
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的rxjs的一个例子:什么是rxjs的OperatorFunction?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 部署SAP UI5应用到ABAP服务器时
- 下一篇: 千元神机要来了?realme真我11系列