这一节介绍RxJs数字类操作符
数字类操作符
计算源 Observable 推送的个数
import { fromEvent, interval } from 'rxjs';
import { count, takeUntil } from 'rxjs/operators';
interval(500).pipe(
takeUntil(fromEvent(document, 'click')),
count()
).subscribe(
res => console.log(res)
); // interva一直运行,直到点击页面,输出点击之前推送数据的个数
增加判断条件
import { range } from 'rxjs';
import { count } from 'rxjs/operators';
const numbers = range(1, 7).pipe(
count(i => i % 2 === 1)
).subscribe(
x => console.log(x)
); // 打印出单数的个数
max/min
求源 Observable 发出的最大/最小值
import { of } from 'rxjs';
import { max, min } from 'rxjs/operators';
of(5, 4, 7, 2, 8).pipe(
// min()
max()
).subscribe(x => console.log(x)); // -> 8
也可以自定义比较规则
interface Person {
age: number;
name: string;
}
import { of } from 'rxjs';
import { max, min } from 'rxjs/operators';
of<Person>(
{age: 5, name: 'Jack'},
{ age: 8, name: 'Rose'},
{ age: 12, name: 'Bob'}
).pipe(
// 这里如果 -1 和 1 的位置对换,则求出的是最小值
// min<Person>((a: Person, b: Person) => a.age > b.age ? 1 : -1)
max<Person>((a: Person, b: Person) => a.age > b.age ? 1 : -1)
).subscribe(
(res: Person) => console.log(res.name)
); // 输出:Bob
前面逍遥乐也分享过一篇文章《史上最全Rxjs从入门到精通的学习知识点整理》,看完这个,你就能熟悉各种rxjs的基本操作了。



最新评论