工具类操作符
Observable
工具箱。类似 console.log
,多用于调试,会返回源 Observable
的值,不转换值
import { fromEvent } from 'rxjs'; import { tap, map } from 'rxjs/operators'; fromEvent(document, 'click').pipe( tap((e: MouseEvent) => console.log(e)), map(e => e.clientX) ).subscribe(x => console.log(x));
delay
Observable
推送的每个值,都延迟一定时间推送,可以指定timeout
,也可以指定未来具体的某个Date
import { fromEvent } from 'rxjs'; import { delay, map } from 'rxjs/operators'; fromEvent(document, 'click').pipe( delay(1000), map((e: MouseEvent) => e.clientX) ).subscribe(x => console.log(x)); // 每次点击都会触发流,但是会等1秒后发出
Date
import { fromEvent } from 'rxjs'; import { delay, map } from 'rxjs/operators'; fromEvent(document, 'click').pipe( delay(new Date('March 15, 2050 12:00:00')), map((e: MouseEvent) => e.clientX) ).subscribe(x => console.log(x)); // 延迟到指定时间才发射出流
timeInterval
将源 Observable
发出的每个值转成一个Object
,包含当前值、与上一次发出值时,经过的时间
import { fromEvent } from 'rxjs'; import { map, timeInterval } from 'rxjs/operators'; fromEvent(document, 'click').pipe( map((e: MouseEvent) => e.clientX), timeInterval() ).subscribe(x => console.log(x)); // 输出:TimeInterval {value: 501, interval: 3408}
timestamp
将源 Observable
发出的每个值转成一个Object
,包含当前值、当前时间戳
import { fromEvent } from 'rxjs'; import { map, timestamp } from 'rxjs/operators'; fromEvent(document, 'click').pipe( map((e: MouseEvent) => e.clientX), timestamp() ).subscribe(x => console.log(x)); // 输出:Timestamp {value: 501, timestamp: 1614156294378}
timeout
在指定时间内,不发出值就报错
import { interval } from 'rxjs'; import { timeout } from 'rxjs/operators'; // 指定时间内 const seconds = interval(1000); seconds.pipe(timeout(1100)) .subscribe( value => console.log(value), // 正常输出 err => console.error(err), // 不会触发 ); // 超过指定时间 seconds.pipe(timeout(900)) .subscribe( value => console.log(value), err => console.error(err) // 直接报错 TimeoutErrorImpl {message: "Timeout has occurred", name: "TimeoutError"} );
也可以指定未来的某个Date
import { interval } from 'rxjs'; import { timeout } from 'rxjs/operators'; interval(1000).pipe( timeout(new Date("December 17, 2020 03:24:00")), ).subscribe( value => console.log(value), // 2020-12-17 03:24:00 前不会报错 err => console.log(err) // 到了2020-12-17 03:24:00就会开始报错了 );
timeoutWith
在指定时间内,不发出值就推送另一个 Observable
const seconds = interval(1000); const minutes = interval(500); // seconds太慢将会推送minutes流 seconds.pipe(timeoutWith(1100, minutes)) .subscribe(value => console.log(value));
前面逍遥乐也分享过一篇文章《史上最全Rxjs从入门到精通的学习知识点整理》,看完这个,你就能熟悉各种rxjs的基本操作了。
最新评论