diff --git a/spec/operators/single-spec.ts b/spec/operators/single-spec.ts index 08befa2064..8b9cb57700 100644 --- a/spec/operators/single-spec.ts +++ b/spec/operators/single-spec.ts @@ -1,3 +1,4 @@ +import {expect} from 'chai'; import * as Rx from '../../dist/cjs/Rx'; import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports @@ -151,4 +152,21 @@ describe('Observable.prototype.single', () => { expectObservable(e1.single(predicate)).toBe(expected, {z: undefined}); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); + + it('should call predicate with indices starting at 0', () => { + const e1 = hot('--a--b--c--|'); + const e1subs = '^ !'; + const expected = '-----------(b|)'; + + let indices = []; + const predicate = function(value, index) { + indices.push(index); + return value === 'b'; + }; + + expectObservable(e1.single(predicate).do(null, null, () => { + expect(indices).to.deep.equal([0, 1, 2]); + })).toBe(expected); + expectSubscriptions(e1.subscriptions).toBe(e1subs); + }); }); \ No newline at end of file diff --git a/src/operator/single.ts b/src/operator/single.ts index 385f2b85da..a1a307753b 100644 --- a/src/operator/single.ts +++ b/src/operator/single.ts @@ -61,19 +61,18 @@ class SingleSubscriber extends Subscriber { } protected _next(value: T): void { - const predicate = this.predicate; - this.index++; - if (predicate) { - this.tryNext(value); + const index = this.index++; + + if (this.predicate) { + this.tryNext(value, index); } else { this.applySingleValue(value); } } - private tryNext(value: T): void { + private tryNext(value: T, index: number): void { try { - const result = this.predicate(value, this.index, this.source); - if (result) { + if (this.predicate(value, index, this.source)) { this.applySingleValue(value); } } catch (err) {