RxJS implements this operator with two variants of sample
.
The first variant accepts as its parameter a periodicity, defined as an integer number of milliseconds,
and it samples the source Observable periodically at that frequency.
Sample Code
var source = Rx.Observable.interval(1000)
.sample(5000)
.take(2);
var subscription = source.subscribe(
function (x) { console.log('Next: ' + x); },
function (err) { console.log('Error: ' + err); },
function () { console.log('Completed'); });
Next: 3
Next: 8
Completed
The second variant accepts as its parameter an Observable, and it samples the source Observable whenever
this second Observable emits an item.
Sample Code
var source = Rx.Observable.interval(1000)
.sample(Rx.Observable.interval(5000))
.take(2);
var subscription = source.subscribe(
function (x) { console.log('Next: ' + x); },
function (err) { console.log('Error: ' + err); },
function () { console.log('Completed'); });
Next: 3
Next: 8
Completed
There is also a throttleFirst
operator, which differs from sample
in that it
emits the first item emitted by the source Observable in each sampling period rather than the
most recently emitted item.
It does not have the variant that uses the emissions from a second Observable to regulate the sampling
periodicity.
Sample Code
var times = [
{ value: 0, time: 100 },
{ value: 1, time: 600 },
{ value: 2, time: 400 },
{ value: 3, time: 900 },
{ value: 4, time: 200 }
];
// Delay each item by time and project value;
var source = Rx.Observable.from(times)
.flatMap(function (item) {
return Rx.Observable
.of(item.value)
.delay(item.time);
})
.throttleFirst(300 /* ms */);
var subscription = source.subscribe(
function (x) { console.log('Next: %s', x); },
function (err) { console.log('Error: %s', err); },
function () { console.log('Completed'); });
Next: 0
Next: 2
Next: 3
Completed
sample
and throttleFirst
operate by default on the timeout
Scheduler . They are found in each of the following distributions:
rx.all.js
rx.all.compat.js
rx.time.js
(requires rx.js
or rx.compat.js
)
rx.lite.js
rx.lite.compat.js