[RxJS] Combination operator: zip

本文详细介绍了RxJS库中的Zip操作符的工作原理及使用方法。通过具体的代码示例展示了如何利用Zip操作符同步地组合多个Observables的最新值,并确保只有当所有输入Observables都发出对应的值时才进行组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CombineLatest and withLatestFrom are both AND-style combination operators. In this lesson, we will learn about zip, our last AND-style combinator. It uses the n-th value of each member Observable to produce the n-th output value.

 

If you zip two observalbe. it will wait both n-th observalbe value emit, and combie them:

  • First of foo + First of bar =  first of output
  • Second of foo + Second of bar = Second of output
  • ...
  • n-th of foo + n-th of bar = n-th of output

It will never combine: n-th of foo + (n+1)-th of bar.

 

var foo = Rx.Observable.of('h', 'e', 'l', 'l', 'o');
var bar = Rx.Observable.interval(400).take(5);

/*
(hello|)                  (foo)
---0---1---2---3---4|     (bar)
  zip((x,y) => x)
---h---e---l---l---o|
*/


//var combined = Rx.Observable.zip(foo, bar, (x,y) => x);
var combined = foo.zip(bar, (x,__)=> x);

combined.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);

  /*
 "next h"
"next e"
"next l"
"next l"
"next o"
"done" 
  */

 

转载于:https://www.cnblogs.com/Answer1215/p/5532381.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值