1 import { Operator } from '../Operator';
2 import { Observable } from '../Observable';
3 import { Subscriber } from '../Subscriber';
4 import { OuterSubscriber } from '../OuterSubscriber';
5 import { InnerSubscriber } from '../InnerSubscriber';
6 import { subscribeToResult } from '../util/subscribeToResult';
8 import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
11 * Emits the most recently emitted value from the source Observable whenever
12 * another Observable, the `notifier`, emits.
14 * <span class="informal">It's like {@link sampleTime}, but samples whenever
15 * the `notifier` Observable emits something.</span>
19 * Whenever the `notifier` Observable emits a value or completes, `sample`
20 * looks at the source Observable and emits whichever value it has most recently
21 * emitted since the previous sampling, unless the source has not emitted
22 * anything since the previous sampling. The `notifier` is subscribed to as soon
23 * as the output Observable is subscribed.
26 * On every click, sample the most recent "seconds" timer
28 * import { fromEvent, interval } from 'rxjs';
29 * import { sample } from 'rxjs/operators';
31 * const seconds = interval(1000);
32 * const clicks = fromEvent(document, 'click');
33 * const result = seconds.pipe(sample(clicks));
34 * result.subscribe(x => console.log(x));
38 * @see {@link debounce}
39 * @see {@link sampleTime}
40 * @see {@link throttle}
42 * @param {Observable<any>} notifier The Observable to use for sampling the
44 * @return {Observable<T>} An Observable that emits the results of sampling the
45 * values emitted by the source Observable whenever the notifier Observable
46 * emits value or completes.
50 export function sample<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T> {
51 return (source: Observable<T>) => source.lift(new SampleOperator(notifier));
54 class SampleOperator<T> implements Operator<T, T> {
55 constructor(private notifier: Observable<any>) {
58 call(subscriber: Subscriber<T>, source: any): TeardownLogic {
59 const sampleSubscriber = new SampleSubscriber(subscriber);
60 const subscription = source.subscribe(sampleSubscriber);
61 subscription.add(subscribeToResult(sampleSubscriber, this.notifier));
67 * We need this JSDoc comment for affecting ESDoc.
71 class SampleSubscriber<T, R> extends OuterSubscriber<T, R> {
73 private hasValue: boolean = false;
75 protected _next(value: T) {
80 notifyNext(outerValue: T, innerValue: R,
81 outerIndex: number, innerIndex: number,
82 innerSub: InnerSubscriber<T, R>): void {
86 notifyComplete(): void {
92 this.hasValue = false;
93 this.destination.next(this.value);