[RxJS] Filtering operators: distinct and distinctUntilChanged

本文介绍了 RxJS 中的 distinct 运算符及其变种 distinctUntilChanged 的使用方法,通过实例展示了如何通过 distinct 过滤重复项,并且演示了如何通过自定义比较函数和刷新函数来实现更复杂的过滤逻辑。

Operator distinct() and its variants are an important type of Filtering operator. This lessons shows how they work and in what cases are they useful.

 

distinctUntilChanged():

var foo = Rx.Observable.interval(500).take(5)
  .zip(Rx.Observable.of('a','b','a','a','b'), (x,y)=>y);

/*
--a--b--a--a--b|
   distinctUntilChanged
--a--b--a-----b|
*/

var result = foo.distinctUntilChanged();

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

 

distinct(comparFn, flushFn):

var foo = Rx.Observable.interval(500).take(5)
  .zip(Rx.Observable.of('a','b','a','a','b'), (x,y)=>y);

/*
--a--b--a--a--b|
   distinct
--a--b---------|
*/

var result = foo.distinct();

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

 

With CamperFn():

var foo = Rx.Observable.interval(500).take(5)
  .zip(Rx.Observable.of('a','b','a','A','b'), (x,y)=>y);


var comparFn = (x, y) => {
  return x.toLowerCase() === y.toLowerCase();
}

/*
--a--b--a--A--b|
   distinct
--a--b---------|
*/

var result = foo.distinct(comparFn);

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

 

with FlusherFn:

var foo = Rx.Observable.interval(500).take(5)
  .zip(Rx.Observable.of('a','b','a','A','b'), (x,y)=>y);


var comparFn = (x, y) => {
  return x.toLowerCase() === y.toLowerCase();
}


var flushFn = Rx.Observable.interval(1100).take(1)
  .concat(Rx.Observable.never());

/*
--a--b--a--A--b|
-------0-------- distinct(comparFn, flushFn) --a--b--a-----b|
*/ var result = foo.distinct(comparFn, flushFn); result.subscribe( function (x) { console.log('next ' + x); }, function (err) { console.log('error ' + err); }, function () { console.log('done'); }, ); /* "next a" "next b" "next a" "next b" "done" */

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值