Skip to content

Function: sample()

sample<T>(period): Operator<T, T>

Defined in: operators/sample.ts:16

Creates a stream operator that emits the most recent value from the source stream at a fixed periodic interval while tracking pending and phantom states.

Values that arrive faster than the period are considered phantoms if skipped, and pending results are tracked in PipeContext until resolved or emitted.

Type Parameters

T

T = any

The type of the values in the source and output streams.

Parameters

period

number

The time in milliseconds between each emission.

Returns

Operator<T, T>

An Operator instance for use in a stream's pipe method.

Examples

From sample.spec.ts:10

typescript
let subject: any = createSubject<number>();

const period = 100;
const sampled = subject.pipe(sample(period));
const results: number[] = [];
(async () => {
  for await (const value of eachValueFrom(sampled)) {
    results.push(value);
  }
})();
subject.next(1);
await new Promise((resolve) => setTimeout(resolve, 50));
subject.next(2);
await new Promise((resolve) => setTimeout(resolve, 125));
subject.next(3);
subject.complete();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(results).toEqual([2, 3]);

Released under the MIT License.