Skip to content

Commit

Permalink
fix(IteratorObservable): get new iterator for each subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
kwonoj committed Aug 15, 2017
1 parent 0212aee commit 02b9ed5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
18 changes: 18 additions & 0 deletions spec/observables/IteratorObservable-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,24 @@ describe('IteratorObservable', () => {
);
});

it('should get new iterator for each subscription', () => {
const expected = [
Rx.Notification.createNext(10),
Rx.Notification.createNext(20),
Rx.Notification.createComplete()
];

const e1 = IteratorObservable.create<number>(new Int32Array([10, 20])).observeOn(rxTestScheduler);

let v1, v2: Array<Rx.Notification<any>>;
e1.materialize().toArray().subscribe((x) => v1 = x);
e1.materialize().toArray().subscribe((x) => v2 = x);

rxTestScheduler.flush();
expect(v1).to.deep.equal(expected);
expect(v2).to.deep.equal(expected);
});

it('should finalize generators if the subscription ends', () => {
const iterator = {
finalized: false,
Expand Down
14 changes: 6 additions & 8 deletions src/observable/IteratorObservable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ interface IteratorObservableState<T> {
* @hide true
*/
export class IteratorObservable<T> extends Observable<T> {
private iterator: Iterator<T>;

static create<T>(iterator: ArrayOrIterable<T> | string, scheduler?: IScheduler): IteratorObservable<T> {
return new IteratorObservable<T>(iterator, scheduler);
}
Expand Down Expand Up @@ -54,20 +52,21 @@ export class IteratorObservable<T> extends Observable<T> {
(<any>this).schedule(state);
}

constructor(iterator: ArrayOrIterable<T> | string, private scheduler?: IScheduler) {
constructor(private readonly iteratorObject: ArrayOrIterable<T> | string, private scheduler?: IScheduler) {
super();

if (iterator == null) {
if (iteratorObject == null) {
throw new Error('iterator cannot be null.');
} else if (!iteratorObject[Symbol_iterator]) {
throw new TypeError('object is not iterable');
}

this.iterator = getIterator(iterator);
}

protected _subscribe(subscriber: Subscriber<T>): TeardownLogic {

let index = 0;
const { iterator, scheduler } = this;
const { scheduler } = this;
const iterator = getIterator(this.iteratorObject);

if (scheduler) {
return scheduler.schedule(IteratorObservable.dispatch, 0, {
Expand Down Expand Up @@ -136,7 +135,6 @@ function getIterator<T>(obj: ArrayOrIterable<T> | string): Iterator<T> {
if (isArrayLike(obj)) {
return new ArrayIterator<T>(<any>obj);
}
throw new TypeError('object is not iterable');
}
return obj[Symbol_iterator]();
}
Expand Down

0 comments on commit 02b9ed5

Please sign in to comment.