PairsObservable.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { Observable } from '../Observable';
  2. function dispatch(state) {
  3. const { obj, keys, length, index, subscriber } = state;
  4. if (index === length) {
  5. subscriber.complete();
  6. return;
  7. }
  8. const key = keys[index];
  9. subscriber.next([key, obj[key]]);
  10. state.index = index + 1;
  11. this.schedule(state);
  12. }
  13. /**
  14. * We need this JSDoc comment for affecting ESDoc.
  15. * @extends {Ignored}
  16. * @hide true
  17. */
  18. export class PairsObservable extends Observable {
  19. constructor(obj, scheduler) {
  20. super();
  21. this.obj = obj;
  22. this.scheduler = scheduler;
  23. this.keys = Object.keys(obj);
  24. }
  25. /**
  26. * Convert an object into an observable sequence of [key, value] pairs
  27. * using an optional IScheduler to enumerate the object.
  28. *
  29. * @example <caption>Converts a javascript object to an Observable</caption>
  30. * var obj = {
  31. * foo: 42,
  32. * bar: 56,
  33. * baz: 78
  34. * };
  35. *
  36. * var source = Rx.Observable.pairs(obj);
  37. *
  38. * var subscription = source.subscribe(
  39. * function (x) {
  40. * console.log('Next: %s', x);
  41. * },
  42. * function (err) {
  43. * console.log('Error: %s', err);
  44. * },
  45. * function () {
  46. * console.log('Completed');
  47. * });
  48. *
  49. * @param {Object} obj The object to inspect and turn into an
  50. * Observable sequence.
  51. * @param {Scheduler} [scheduler] An optional IScheduler to run the
  52. * enumeration of the input sequence on.
  53. * @returns {(Observable<Array<string | T>>)} An observable sequence of
  54. * [key, value] pairs from the object.
  55. */
  56. static create(obj, scheduler) {
  57. return new PairsObservable(obj, scheduler);
  58. }
  59. /** @deprecated internal use only */ _subscribe(subscriber) {
  60. const { keys, scheduler } = this;
  61. const length = keys.length;
  62. if (scheduler) {
  63. return scheduler.schedule(dispatch, 0, {
  64. obj: this.obj, keys, length, index: 0, subscriber
  65. });
  66. }
  67. else {
  68. for (let idx = 0; idx < length; idx++) {
  69. const key = keys[idx];
  70. subscriber.next([key, this.obj[key]]);
  71. }
  72. subscriber.complete();
  73. }
  74. }
  75. }
  76. //# sourceMappingURL=PairsObservable.js.map