| 1 |
import { innerFrom } from '../observable/innerFrom'; |
| 2 |
import { MonoTypeOperatorFunction, ObservableInput } from '../types'; |
| 3 |
import { operate } from '../util/lift'; |
| 4 |
import { noop } from '../util/noop'; |
| 5 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 6 |
|
| 7 |
/** |
| 8 |
* Emits the most recently emitted value from the source Observable whenever |
| 9 |
* another Observable, the `notifier`, emits. |
| 10 |
* |
| 11 |
* <span class="informal">It's like {@link sampleTime}, but samples whenever |
| 12 |
* the `notifier` `ObservableInput` emits something.</span> |
| 13 |
* |
| 14 |
*  |
| 15 |
* |
| 16 |
* Whenever the `notifier` `ObservableInput` emits a value, `sample` |
| 17 |
* looks at the source Observable and emits whichever value it has most recently |
| 18 |
* emitted since the previous sampling, unless the source has not emitted |
| 19 |
* anything since the previous sampling. The `notifier` is subscribed to as soon |
| 20 |
* as the output Observable is subscribed. |
| 21 |
* |
| 22 |
* ## Example |
| 23 |
* |
| 24 |
* On every click, sample the most recent `seconds` timer |
| 25 |
* |
| 26 |
* ```ts |
| 27 |
* import { fromEvent, interval, sample } from 'rxjs'; |
| 28 |
* |
| 29 |
* const seconds = interval(1000); |
| 30 |
* const clicks = fromEvent(document, 'click'); |
| 31 |
* const result = seconds.pipe(sample(clicks)); |
| 32 |
* |
| 33 |
* result.subscribe(x => console.log(x)); |
| 34 |
* ``` |
| 35 |
* |
| 36 |
* @see {@link audit} |
| 37 |
* @see {@link debounce} |
| 38 |
* @see {@link sampleTime} |
| 39 |
* @see {@link throttle} |
| 40 |
* |
| 41 |
* @param notifier The `ObservableInput` to use for sampling the |
| 42 |
* source Observable. |
| 43 |
* @return A function that returns an Observable that emits the results of |
| 44 |
* sampling the values emitted by the source Observable whenever the notifier |
| 45 |
* Observable emits value or completes. |
| 46 |
*/ |
| 47 |
export function sample<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> { |
| 48 |
return operate((source, subscriber) => { |
| 49 |
let hasValue = false; |
| 50 |
let lastValue: T | null = null; |
| 51 |
source.subscribe( |
| 52 |
createOperatorSubscriber(subscriber, (value) => { |
| 53 |
hasValue = true; |
| 54 |
lastValue = value; |
| 55 |
}) |
| 56 |
); |
| 57 |
innerFrom(notifier).subscribe( |
| 58 |
createOperatorSubscriber( |
| 59 |
subscriber, |
| 60 |
() => { |
| 61 |
if (hasValue) { |
| 62 |
hasValue = false; |
| 63 |
const value = lastValue!; |
| 64 |
lastValue = null; |
| 65 |
subscriber.next(value); |
| 66 |
} |
| 67 |
}, |
| 68 |
noop |
| 69 |
) |
| 70 |
); |
| 71 |
}); |
| 72 |
} |