Demo:  sample

The sample is a time-interval filter that emits the latest values from source, as and when the specified inner observable emits a value.

It is similar to sampleTime.The difference being, we can specify a dynamic sampling interval using an inner observable, instead of the time in milliseconds as in sampleTime.

//sample every 2 sec
sample(interval(2000))
//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))));

//emits the latest value, every 2 sec
const timeIntervalFilter = sample(interval(2000));

const output = source.pipe(timeIntervalFilter).subscribe(v=>console.log(v))
What is happening ?

The sample is a time-interval filter that emits the latest values from source:

  • as and when the specified inner observable emits a value.

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 sample with inner observable, interval of 2 seconds. Here the sampling points will be decided by the inner observable, as and when it emits a value. So, for our case it is at the end of every 2 seconds. 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.