[RxJS] Transformation operator: buffer, bufferCount, bufferTime

RxJS缓冲操作符详解
本文详细介绍了RxJS中的缓冲操作符buffer及其变体bufferTime、bufferCount的使用方法。通过具体的示例代码展示了如何利用这些操作符来按特定条件组合连续的数据项,并将输出作为数组发射。

This lesson will teach you about another horizontal combination operator: buffer and its variants. Buffer groups consecutive values together, emitting the output as an array. The buffer variants and their arguments allow to specify when to close the buffers.

 

buffer(close observable): According to another observalbe to group items.

var foo = Rx.Observable.of('h', 'e', 'l', 'l', 'o')
  .zip(Rx.Observable.interval(600).take(5), (x,y) => x);
var bar = Rx.Observable.interval(900).take(3);

/*
-----h-----e-----l-----l-----o|       (foo)
--------0--------1--------2|          (bar)

        buffer(bar)

--------h--------e--------ll|
*/

var result = foo.buffer(bar);

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

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

 

bufferTime(number): 

var foo = Rx.Observable.of('h', 'e', 'l', 'l', 'o')
  .zip(Rx.Observable.interval(600).take(5), (x,y) => x);

/*
-----h-----e-----l-----l-----o|       (foo)
--------x--------x--------x|          (900ms)

        bufferTime(900)

--------h--------e--------ll|
*/

var result = foo.bufferTime(900);

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

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

 

bufferCount(number):

var foo = Rx.Observable.of('h', 'e', 'l', 'l', 'o')
  .zip(Rx.Observable.interval(600).take(5), (x,y) => x);

/*
-----h-----e-----l-----l-----o|       (foo)

        bufferCount(2)

----------([h,e])------([l,l])([o|])l
*/

var result = foo.bufferCount(2);

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

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

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值