| 1 |
import { reduce } from './reduce'; |
| 2 |
import { OperatorFunction } from '../types'; |
| 3 |
import { operate } from '../util/lift'; |
| 4 |
|
| 5 |
const arrReducer = (arr: any[], value: any) => (arr.push(value), arr); |
| 6 |
|
| 7 |
/** |
| 8 |
* Collects all source emissions and emits them as an array when the source completes. |
| 9 |
* |
| 10 |
* <span class="informal">Get all values inside an array when the source completes</span> |
| 11 |
* |
| 12 |
*  |
| 13 |
* |
| 14 |
* `toArray` will wait until the source Observable completes before emitting |
| 15 |
* the array containing all emissions. When the source Observable errors no |
| 16 |
* array will be emitted. |
| 17 |
* |
| 18 |
* ## Example |
| 19 |
* |
| 20 |
* ```ts |
| 21 |
* import { interval, take, toArray } from 'rxjs'; |
| 22 |
* |
| 23 |
* const source = interval(1000); |
| 24 |
* const example = source.pipe( |
| 25 |
* take(10), |
| 26 |
* toArray() |
| 27 |
* ); |
| 28 |
* |
| 29 |
* example.subscribe(value => console.log(value)); |
| 30 |
* |
| 31 |
* // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 32 |
* ``` |
| 33 |
* |
| 34 |
* @return A function that returns an Observable that emits an array of items |
| 35 |
* emitted by the source Observable when source completes. |
| 36 |
*/ |
| 37 |
export function toArray<T>(): OperatorFunction<T, T[]> { |
| 38 |
// Because arrays are mutable, and we're mutating the array in this |
| 39 |
// reducer process, we have to encapsulate the creation of the initial |
| 40 |
// array within this `operate` function. |
| 41 |
return operate((source, subscriber) => { |
| 42 |
reduce(arrReducer, [] as T[])(source).subscribe(subscriber); |
| 43 |
}); |
| 44 |
} |