如果没有匹配的累加器,RxJS 如何减少? [英] How does RxJS reduce in case there is no matching accumulator?

查看:39
本文介绍了如果没有匹配的累加器,RxJS 如何减少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一篇关于反应式编程的文章在 JavaScript 中 并且不确定在那里列出的以下示例如何导致输出 27

I was going through an article on Reactive Programming in JavaScript and not sure how the following example listed in there results in output 27

import {Observable} from 'rxjs-es';

let output = Observable.interval(500)
             .map(i => [1,2,3,4,5,6][i]);

let result = output.map(num1 => num1)
    .filter(num1 => num1 > 4)
    .reduce((num1, num2) => num1 + num2);

result.subscribe(number => console.log(number));

Output --> 27

根据我的理解,每隔 500 毫秒,流 [1,2,3,4,5,6] 中的每个数字都会被一一过滤.因此,只有 5 和 6 将能够通过过滤器.

As per my understanding at every 500ms interval, each of the numbers in the stream [1,2,3,4,5,6] gets filtered one by one. So, only 5 and 6 will be able to go through the filter.

然而,由于在处理过程中的任何给定点只有一个元素可用,我想知道reduce是如何将结果累积为27的?

However, since only one element would be available at any given point during the processing, I wonder how the reduce is accumulating the result as 27?

推荐答案

我已经把它翻译成 RxJs 6 并且它不输出 27

I have translated it to RxJs 6 and it doesn't output 27

const { interval } = rxjs;
const { map, filter, reduce, take } = rxjs.operators;

let output = interval(500).pipe(
 map(i => [1,2,3,4,5,6][i]), // very strange way of adding one to the interval
 take(6) // had to add a take so observable would complete else reduce would never emit
);

let result = output.pipe(
  map(num1 => num1), // Does nothing
  filter(num1 => num1 > 4), // filters out those less than 5
  reduce((num1, num2) => num1 + num2) // add the leftovers 5 and 6
);

result.subscribe(number => console.log(number)); // 11 is the output

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"></script>

这篇关于如果没有匹配的累加器,RxJS 如何减少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆