[RxJS] Transformation operators: delay and delayWhen

This lessons teaches about delay and delayWhen: simple operators that time shift.

 

delay(number | date)

var foo = Rx.Observable.interval(500).take(5);

/*
--0--1--2--3--4|
 delay(1000)
-----0--1--2--3--4|
*/

// delay(1000)
var result = foo.delay(1000);

result.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);
var foo = Rx.Observable.interval(500).take(5);

/*
--0--1--2--3--4|
 delay(date)
-----0--1--2--3--4|
*/


var date = new Date(new Date().getTime() + 1000); 
var result = foo.delay(date);

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

 

 

delayWhen( function :Observable): accept a function which return an observable:

var foo = Rx.Observable.interval(500).take(5);

/*
--0--1--2--3--4|
 delayWhen(x => --------0--------...)
--------0--------1--------2--------3--------4|
*/

// delay(1000)
var result = foo.delayWhen(x =>
  Rx.Observable.interval(x * 1000) // For each foo, it will delay 1000 * x, so '2' --> 2000, '3' ---> 3000
);

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

 

你可能感兴趣的:([RxJS] Transformation operators: delay and delayWhen)