RxJS Mastery – #48 sample and sampleTime

RxJS Mastery lesson title sample and sampleTime operator

The RxJS sample and sampleTime operators are filtering operators that emit the most recent value from the source. For sample this is based on the emission of another Observable while for sampleTime it is based on a defined time frame.

RxJS sample emits the most recent value based on a notifier

The only parameter of sample is the notifier. This Observable determines the emitted values in the final output. Whenever the notifier emits, the most recent value from the source (if any were emitted) is also emitted.

In the below example, the notifier emits every second time frame. As a consequence the values a, b, and f are part of the final result Observable.

const source$ = cold('  abcdefg|');
const notifier$ = cold('-n-n-n-n-n');
const expected =       '-b-d-f-|';


Because the source Observable has already completed when the notifier emits a fourth time, g is not part of the output.

RxJS sampleTime samples the source Observable at periodic time intervals

If you would like to have the most recent value of the source every x millisecond, then sampleTime is your operator. In the below example, we sample the same values as above in the non-time operator case. Sampling every 2 ms leaves us also with the values b, d, and f.

const source$ = cold('  -abcdefg|');
const expected =       '--b-d-f-|';


Exercise for the RxJS sample and sampleTime operator 💪

Use the sample operator (and interval) to create a little buzzer game in the browser:

The goal is to come as close to the target as possible. You have 3 buttons. First, prepare sets a target, i.e. a random integer between 1 and 10. A click on the start button will start the timer. Finally, a click on the check button will show the difference to the target. A starter template for the exercise can be found here.

As always the code examples can be found on GitHub.