@reactivex/rxjs
Version:
Reactive Extensions for modern JavaScript
91 lines • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var Observable_1 = require("../Observable");
var Subscription_1 = require("../Subscription");
/**
* Convert an object into an Observable of `[key, value]` pairs.
*
* <span class="informal">Turn entries of an object into a stream.</span>
*
* <img src="./img/pairs.png" width="100%">
*
* `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each
* emitted array has exactly two elements - the first is a key from the object
* and the second is a value corresponding to that key. Keys are extracted from
* an object via `Object.keys` function, which means that they will be only
* enumerable keys that are present on an object directly - not ones inherited
* via prototype chain.
*
* By default these arrays are emitted synchronously. To change that you can
* pass a {@link SchedulerLike} as a second argument to `pairs`.
*
* @example <caption>Converts a javascript object to an Observable</caption>
* ```ts
* import { pairs } from 'rxjs';
*
* const obj = {
* foo: 42,
* bar: 56,
* baz: 78
* };
*
* pairs(obj)
* .subscribe(
* value => console.log(value),
* err => {},
* () => console.log('the end!')
* );
*
* // Logs:
* // ["foo", 42],
* // ["bar", 56],
* // ["baz", 78],
* // "the end!"
* ```
*
* @param {Object} obj The object to inspect and turn into an
* Observable sequence.
* @param {Scheduler} [scheduler] An optional IScheduler to schedule
* when resulting Observable will emit values.
* @returns {(Observable<Array<string|T>>)} An observable sequence of
* [key, value] pairs from the object.
*/
function pairs(obj, scheduler) {
if (!scheduler) {
return new Observable_1.Observable(function (subscriber) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length && !subscriber.closed; i++) {
var key = keys[i];
if (obj.hasOwnProperty(key)) {
subscriber.next([key, obj[key]]);
}
}
subscriber.complete();
});
}
else {
return new Observable_1.Observable(function (subscriber) {
var keys = Object.keys(obj);
var subscription = new Subscription_1.Subscription();
subscription.add(scheduler.schedule(dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj }));
return subscription;
});
}
}
exports.pairs = pairs;
/** @internal */
function dispatch(state) {
var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj;
if (!subscriber.closed) {
if (index < keys.length) {
var key = keys[index];
subscriber.next([key, obj[key]]);
subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj }));
}
else {
subscriber.complete();
}
}
}
exports.dispatch = dispatch;
//# sourceMappingURL=pairs.js.map