buffer.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { OuterSubscriber } from '../OuterSubscriber';
  2. import { subscribeToResult } from '../util/subscribeToResult';
  3. /**
  4. * Buffers the source Observable values until `closingNotifier` emits.
  5. *
  6. * <span class="informal">Collects values from the past as an array, and emits
  7. * that array only when another Observable emits.</span>
  8. *
  9. * <img src="./img/buffer.png" width="100%">
  10. *
  11. * Buffers the incoming Observable values until the given `closingNotifier`
  12. * Observable emits a value, at which point it emits the buffer on the output
  13. * Observable and starts a new buffer internally, awaiting the next time
  14. * `closingNotifier` emits.
  15. *
  16. * @example <caption>On every click, emit array of most recent interval events</caption>
  17. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18. * var interval = Rx.Observable.interval(1000);
  19. * var buffered = interval.buffer(clicks);
  20. * buffered.subscribe(x => console.log(x));
  21. *
  22. * @see {@link bufferCount}
  23. * @see {@link bufferTime}
  24. * @see {@link bufferToggle}
  25. * @see {@link bufferWhen}
  26. * @see {@link window}
  27. *
  28. * @param {Observable<any>} closingNotifier An Observable that signals the
  29. * buffer to be emitted on the output Observable.
  30. * @return {Observable<T[]>} An Observable of buffers, which are arrays of
  31. * values.
  32. * @method buffer
  33. * @owner Observable
  34. */
  35. export function buffer(closingNotifier) {
  36. return function bufferOperatorFunction(source) {
  37. return source.lift(new BufferOperator(closingNotifier));
  38. };
  39. }
  40. class BufferOperator {
  41. constructor(closingNotifier) {
  42. this.closingNotifier = closingNotifier;
  43. }
  44. call(subscriber, source) {
  45. return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
  46. }
  47. }
  48. /**
  49. * We need this JSDoc comment for affecting ESDoc.
  50. * @ignore
  51. * @extends {Ignored}
  52. */
  53. class BufferSubscriber extends OuterSubscriber {
  54. constructor(destination, closingNotifier) {
  55. super(destination);
  56. this.buffer = [];
  57. this.add(subscribeToResult(this, closingNotifier));
  58. }
  59. _next(value) {
  60. this.buffer.push(value);
  61. }
  62. notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  63. const buffer = this.buffer;
  64. this.buffer = [];
  65. this.destination.next(buffer);
  66. }
  67. }
  68. //# sourceMappingURL=buffer.js.map