W3cubDocs

/RxJS

sample

function stable

Emits the most recently emitted value from the source Observable whenever another Observable, the notifier, emits.

sample<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T>

Parameters

notifier

The Observable to use for sampling the source Observable.

Returns

MonoTypeOperatorFunction<T>: An Observable that emits the results of sampling the values emitted by the source Observable whenever the notifier Observable emits value or completes.

Description

It's like sampleTime, but samples whenever the notifier Observable emits something.

sample marble diagram

Whenever the notifier Observable emits a value or completes, sample looks at the source Observable and emits whichever value it has most recently emitted since the previous sampling, unless the source has not emitted anything since the previous sampling. The notifier is subscribed to as soon as the output Observable is subscribed.

Example

On every click, sample the most recent "seconds" timer

import { fromEvent, interval } from 'rxjs';
import { sample } from 'rxjs/operators';

const seconds = interval(1000);
const clicks = fromEvent(document, 'click');
const result = seconds.pipe(sample(clicks));
result.subscribe(x => console.log(x));

See Also

© 2015–2018 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/operators/sample