Rxjs Observable.pipe 传入多个 operators 的执行逻辑分析

测试代码:

fromEvent(this.test, 'click').pipe(map( event => event.timeStamp), mapTo(1)).subscribe((event) => console.log(event));

pipe 操作的两个输入操作:

输入参数为数组,包含两个元素:

使用原始的 Observable 作为输入,执行这两个操作:

数组的 reduce 是一个原生方法:

下面这段代码,介绍了 reduce 的用法:

<html>
<script>

var a = [1,2,3,4];

function fn(pre, cur, index, arr){
	console.log(`previous: ${pre}, cur: ${cur},
		index: ${index}, whole arr: ${arr}`);
	return pre + cur;
}

console.log(a.reduce( fn, 0));

</script>
</html>

reduce 接受两个参数,第一个参数是一个函数,该函数接收 4 个输入参数,previous,current,index 和 array:

  • previous:前一轮 reduce 迭代值,如果第一轮,则该值为第二个参数,即初始值
  • current:当前这轮的 reduce 迭代值。例如,array 元素为1,2,3,4,则 reduce 每轮迭代,current 值分别为1,2,3,4
  • index:迭代的索引值
  • array:调用 reduce 的原始数组,配合前一个 index 参数,能访问整个数组的内容

在实际使用过程中,previous 和 current 这两个参数用的最多。

回到 pipeFromArray 的实现。

reduce 第一轮迭代:

prev 是 input 传入的初始值,fn 是输入 fns 数组的第一个元素。即第一个 map 返回的 operator:

这里不会执行具体的 map 操作,而是返回一个新的 Observable 对象,作为第二轮 reduce 迭代的输入:

lift 方法就是返回新的 Observable 对象:

mapTo 的实现:

经过 pipe 处理过的 Observable,最后应用程序订阅的,就是这个最终版的 Observable:

更多Jerry的原创文章,尽在:"汪子熙":

posted @ 2021-06-16 14:09  汪子熙  阅读(204)  评论(0编辑  收藏  举报