codecamp

RxJS count

计算源的发射数量,当源完成。

count<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, number>

参量

谓词 可选的。 默认值为 undefined。 一种 布尔函数,用于选择要计算的值。 它提供了 参数: value:来自可观察来源的值。 index:来自源 Observable 的值的(从零开始的)“索引”。 source:源 Observable 实例本身。

returns

OperatorFunction<T, number>:一个数字的 Observable,代表计数为 如上所述。

描述

告诉您在什么时候发出了多少个值 完成。

count marble diagram

count将发出值的 Observable 转换为 发出一个值,该值代表 来源可观察。 如果源 Observable 因错误而终止, count 将传递此错误通知,而无需先发出值。 如果 源 Observable 根本不会终止, count也不会发出 一个值也不终止。 该运算符具有可选 predicate功能 作为参数,在这种情况下,输出排放将代表 源值匹配 truepredicate

例子

计算第一次点击之前经过了多少秒

import { fromEvent, interval } from 'rxjs';
import { count, takeUntil } from 'rxjs/operators';


const seconds = interval(1000);
const clicks = fromEvent(document, 'click');
const secondsBeforeClick = seconds.pipe(takeUntil(clicks));
const result = secondsBeforeClick.pipe(count());
result.subscribe(x => console.log(x));

计算1到7之间有多少个奇数

import { range } from 'rxjs';
import { count } from 'rxjs/operators';


const numbers = range(1, 7);
const result = numbers.pipe(count(i => i % 2 === 1));
result.subscribe(x => console.log(x));
// Results in:
// 4

也可以看看

RxJS concatMapTo
RxJS debounce
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

RxJS operators

RxJS fetch

RxJS testing

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }