[RxJS] Filtering operators: takeUntil, takeWhile

take(), takeLast(), first(), last(), those opreators all take number or no param. takeUtil and takeWhile will take Observalbe and function.

 

takeUntil(notifier: Observable): Stop when another observalbe happens

var foo = Rx.Observable.interval(1000);
var btn = document.querySelector('#stop');
var stop$ = Rx.Observable.fromEvent(btn, 'click');
/*
--0--1--2--3--4--5--6--7--...
       takeUntil()
--0--1--2--3--4|
*/

var bar = foo.takeUntil(stop$);

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

  /*
"next 0"
"next 1"
"next 2"
"next 3"
"next 4"
"done"
  */

 

 

takeWhile(predicate: function): Abort when it meets the predicate function.

var foo = Rx.Observable.interval(1000);
/*
--0--1--2--3--4--5--6--7--...
       takeWhile(x => x < 3)
--0--1--2--|
*/

var bar = foo.takeWhile((x)=>{
             return x<3;             
         });

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

  /*
"next 0"
"next 1"
"next 2"
"done"
  */

 

posted @ 2016-05-25 18:17  Zhentiw  阅读(461)  评论(0编辑  收藏  举报