c8773d46aef263480ad7cfbe643c6c322fd219ed00188796537b46b733a9f5a75fd50ed92b48ad805c43603001fd4a50c7ba6d68c135959b4e50b75cf7a32d 1.3 KB

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