| 1 |
import { OperatorFunction, ObservableInput } from '../types'; |
| 2 |
import { operate } from '../util/lift'; |
| 3 |
import { noop } from '../util/noop'; |
| 4 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 5 |
import { innerFrom } from '../observable/innerFrom'; |
| 6 |
|
| 7 |
/** |
| 8 |
* Buffers the source Observable values until `closingNotifier` emits. |
| 9 |
* |
| 10 |
* <span class="informal">Collects values from the past as an array, and emits |
| 11 |
* that array only when another Observable emits.</span> |
| 12 |
* |
| 13 |
*  |
| 14 |
* |
| 15 |
* Buffers the incoming Observable values until the given `closingNotifier` |
| 16 |
* `ObservableInput` (that internally gets converted to an Observable) |
| 17 |
* emits a value, at which point it emits the buffer on the output |
| 18 |
* Observable and starts a new buffer internally, awaiting the next time |
| 19 |
* `closingNotifier` emits. |
| 20 |
* |
| 21 |
* ## Example |
| 22 |
* |
| 23 |
* On every click, emit array of most recent interval events |
| 24 |
* |
| 25 |
* ```ts |
| 26 |
* import { fromEvent, interval, buffer } from 'rxjs'; |
| 27 |
* |
| 28 |
* const clicks = fromEvent(document, 'click'); |
| 29 |
* const intervalEvents = interval(1000); |
| 30 |
* const buffered = intervalEvents.pipe(buffer(clicks)); |
| 31 |
* buffered.subscribe(x => console.log(x)); |
| 32 |
* ``` |
| 33 |
* |
| 34 |
* @see {@link bufferCount} |
| 35 |
* @see {@link bufferTime} |
| 36 |
* @see {@link bufferToggle} |
| 37 |
* @see {@link bufferWhen} |
| 38 |
* @see {@link window} |
| 39 |
* |
| 40 |
* @param closingNotifier An `ObservableInput` that signals the |
| 41 |
* buffer to be emitted on the output Observable. |
| 42 |
* @return A function that returns an Observable of buffers, which are arrays |
| 43 |
* of values. |
| 44 |
*/ |
| 45 |
export function buffer<T>(closingNotifier: ObservableInput<any>): OperatorFunction<T, T[]> { |
| 46 |
return operate((source, subscriber) => { |
| 47 |
// The current buffered values. |
| 48 |
let currentBuffer: T[] = []; |
| 49 |
|
| 50 |
// Subscribe to our source. |
| 51 |
source.subscribe( |
| 52 |
createOperatorSubscriber( |
| 53 |
subscriber, |
| 54 |
(value) => currentBuffer.push(value), |
| 55 |
() => { |
| 56 |
subscriber.next(currentBuffer); |
| 57 |
subscriber.complete(); |
| 58 |
} |
| 59 |
) |
| 60 |
); |
| 61 |
|
| 62 |
// Subscribe to the closing notifier. |
| 63 |
innerFrom(closingNotifier).subscribe( |
| 64 |
createOperatorSubscriber( |
| 65 |
subscriber, |
| 66 |
() => { |
| 67 |
// Start a new buffer and emit the previous one. |
| 68 |
const b = currentBuffer; |
| 69 |
currentBuffer = []; |
| 70 |
subscriber.next(b); |
| 71 |
}, |
| 72 |
noop |
| 73 |
) |
| 74 |
); |
| 75 |
|
| 76 |
return () => { |
| 77 |
// Ensure buffered values are released on finalization. |
| 78 |
currentBuffer = null!; |
| 79 |
}; |
| 80 |
}); |
| 81 |
} |