1 import { Operator } from '../Operator';
2 import { Observable } from '../Observable';
3 import { Subscriber } from '../Subscriber';
5 import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
6 import { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';
9 * Emits the most recently emitted value from the source Observable whenever
10 * another Observable, the `notifier`, emits.
12 * <span class="informal">It's like {@link sampleTime}, but samples whenever
13 * the `notifier` Observable emits something.</span>
17 * Whenever the `notifier` Observable emits a value or completes, `sample`
18 * looks at the source Observable and emits whichever value it has most recently
19 * emitted since the previous sampling, unless the source has not emitted
20 * anything since the previous sampling. The `notifier` is subscribed to as soon
21 * as the output Observable is subscribed.
24 * On every click, sample the most recent "seconds" timer
26 * import { fromEvent, interval } from 'rxjs';
27 * import { sample } from 'rxjs/operators';
29 * const seconds = interval(1000);
30 * const clicks = fromEvent(document, 'click');
31 * const result = seconds.pipe(sample(clicks));
32 * result.subscribe(x => console.log(x));
36 * @see {@link debounce}
37 * @see {@link sampleTime}
38 * @see {@link throttle}
40 * @param {Observable<any>} notifier The Observable to use for sampling the
42 * @return {Observable<T>} An Observable that emits the results of sampling the
43 * values emitted by the source Observable whenever the notifier Observable
44 * emits value or completes.
48 export function sample<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T> {
49 return (source: Observable<T>) => source.lift(new SampleOperator(notifier));
52 class SampleOperator<T> implements Operator<T, T> {
53 constructor(private notifier: Observable<any>) {
56 call(subscriber: Subscriber<T>, source: any): TeardownLogic {
57 const sampleSubscriber = new SampleSubscriber(subscriber);
58 const subscription = source.subscribe(sampleSubscriber);
59 subscription.add(innerSubscribe(this.notifier, new SimpleInnerSubscriber(sampleSubscriber)));
65 * We need this JSDoc comment for affecting ESDoc.
69 class SampleSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {
71 private hasValue: boolean = false;
73 protected _next(value: T) {
82 notifyComplete(): void {
88 this.hasValue = false;
89 this.destination.next!(this.value!);