利用宝珠图理解RXJS的操作符

840 阅读2分钟

rxjs,作为响应式编程的js实现,在目前前端算是比较新奇的概念,加上网上的中文资料还不是很详尽,对初学者还是有些难度,所以采用宝珠图来理解RxJs是一个比较简单的入门方法。

首先,利用‘时间’这个维度来理解流

<body>
<div>高度:<input id="height" type="number"></div>
<div>宽度:<input id="width" type="number"></div>
<div>面积:<span id="area"></span></div>
</body>
<script>
const { fromEvent, combineLatest } = rxjs;
const { pluck } = rxjs.operators;
 
const height = document.getElementById("height");
const width = document.getElementById("width");
const area = document.getElementById("area");
const height$ = fromEvent(height, 'keyup').pipe(pluck("target", "value"));
const width$ = fromEvent(width, 'keyup').pipe(pluck("target", "value"));
const area$ = combineLatest(height$, width$, (h, w) => { return h * w })
area$.subscribe(val => area.innerHTML = val)
</script>

combineLatest操作符会取到流的最新的值,上面这个gif的操作,如果画成简易的宝珠图就是以下:

height:-------1---------------------------------3-----------------------------------

width: ---------------------2--------------------------------------------3----------

area:------------------- 1 * 2 = 2-----------3 * 2 = 6-----------------3 * 3 = 9---

所以,如果我们用‘时间’的推移来理解流的变化,我们就能清楚的理解combineLatest操作符起到的作用。

再来理解zip操作符,还是原来的代码,只是操作符换成zip:

<body>
  <div>高度:<input id="height" type="number"></div>
  <div>宽度:<input id="width" type="number"></div>
  <div>面积:<span id="area"></span></div>
</body>
<script>
  const { fromEvent, zip} = rxjs;
  const { pluck } = rxjs.operators;
 
  const height = document.getElementById("height");
  const width = document.getElementById("width");
  const area = document.getElementById("area");
  const height$ = fromEvent(height, 'keyup').pipe(pluck("target", "value"));
  const width$ = fromEvent(width, 'keyup').pipe(pluck("target", "value"));
  const area$ = zip(height$, width$, (h, w) => { return h * w })
  area$.subscribe(val => area.innerHTML = val)
</script>

我们能看到当高度改变2时,面积不会马上改变,需要当宽度也改变时面积才会改变,也就是需要按照出场顺序成对改变。所以我们能在gif效果图中看到后面的6*4=16这样的假象,不要被蒙蔽,用宝珠图来解释:

height:----1---------2--------3--------4------5------6-------------------------------------------

width: ---------1---------2---------3----------------------4----------5----------6---------------

area:--------1* 1=1-----2* 2=4----3* 3=9-------------4* 4=16---5* 5=25----6* 6=36--------

通过宝珠图,我们知道zip这个操作符,它合并两个流时,不是合并最新值,而是合并出场顺序一样的两个值。所以当width输入4的时候,4是width输入框第四次输入的值,所以他会在height找第四次发生改变的值(这个值也是4),所以面积是4*4=16。

所以利用‘时间维度’这个概念,和宝珠图来理解rxjs,我们就能更好的理解流里面发生的什么事情。不会因为抽象的概念和奇怪的结果而痛苦。

这里分享一个线上的宝珠图链接,现在我们可以轻松学习rx的各种操作符了