Demo: sampleTime
sampleTime is a time-interval filter that emits the latest values periodically, at the end of every sampling time intervals.
sampleTime(periodicSamplingIntervalInMilliseconds)
It suitable for sampling contineous streams like stock quotes, weather updates etc.
//Each item is delayed by v*100 milliseconds
const source = of(2,5,15,25,4,45,5,6)
.pipe(concatMap(v=>of(v).pipe(delay(100*v))));
//Sample time emits the latest values, at the end of every 2 sec
const timeIntervalFilter = sampleTime(2000);
const output = source.pipe(timeIntervalFilter).subscribe(v=>console.log(v))
The sampleTime is a time-interval filter that emits the latest values periodically: at the end of every sampling time interval.
It's a very commonly used sampling technique.
Let's look at the demo to verify how it works: For the demo we are using sampling with intervals of 2 seconds. Unlike the other time Interval Filter in rxjs, the "sample Time" filter is independent of the arrival of the source items. It starts as soon as the subscription starts. Also, ends abruptly as the subscription completes. As we can see it's emmiting the latest values at the end of every 2 second interval. For the first interval we have 2 & 5 with 5 being the latest. For the second one we have 15. For the 3rd one we have 25 & 4, 4 being the latest. For the 4th one we do not have any value to emit, hence goes blank. For the 5th one it's 45, the only value. Importantly for the sixth one, since the source completed:
- It could not sample 6, because the sampling interval did not reach it's end.
Unlike auditTime, throttleTime and debounceTime, the sampleTime intervals are independent of the timing of the incoming values.
We can use sampleTime to filter and collect the values at the end of regular periodic intervals.
Usages
1. Sample at regular periodic intervals
Let's say we are sourcing NASDAQ index values every 5 sec for our realtime analysis. But, we want to save it every 15 sec for our historical analysis. We can use sampleTime as shown below to save our data every 15 sec.
Stackblitzimport { interval, sampleTime , scan , tap } from 'rxjs';
const mockUnitChange = () => Math.round( Math.random()*10 - 4);
//Emits random values around 30000, every 5 sec
const mockSource = interval(5000).pipe(
scan( (acc, v) => acc + mockUnitChange(), 30000 ),
tap(v => console.log("source value :" + v) ),
);
//Filter the source and emits the latest values, every 15 sec
const sampleToSave = mockSource.pipe(
sampleTime(15000),
tap(v => console.log("sample for saving :" + v) ),
);
sampleToSave.subscribe( x => console.log("sample for saving :" + x) );
Output : source values come every 5sec and samples are taken at the end of every 15 sec.
source value :29997
source value :30000
source value :30001
sample for saving :30001
source value :29998
source value :29999
source value :30005
sample for saving :30005