Skip to content

Commit a047e7a

Browse files
benleshjayphelps
authored andcommitted
fix(first): will now only emit one value in recursive cases (#2100)
adds guard after first emitted value to prevent reentrant behavior fixes #2098
1 parent c83bab9 commit a047e7a

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

spec/operators/first-spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,20 @@ describe('Observable.prototype.first', () => {
4242
expectSubscriptions(e1.subscriptions).toBe(sub);
4343
});
4444

45+
it('should only emit one value in recursive cases', () => {
46+
const subject = new Rx.Subject<number>();
47+
const results = [];
48+
49+
subject.first().subscribe(x => {
50+
results.push(x);
51+
subject.next(x + 1);
52+
});
53+
54+
subject.next(0);
55+
56+
expect(results).to.deep.equal([0]);
57+
});
58+
4559
it('should propagate error from the source observable', () => {
4660
const e1 = hot('---^---#');
4761
const expected = '----#';

src/operator/first.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ class FirstOperator<T, R> implements Operator<T, R> {
8585
class FirstSubscriber<T, R> extends Subscriber<T> {
8686
private index: number = 0;
8787
private hasCompleted: boolean = false;
88+
private _emitted: boolean = false;
8889

8990
constructor(destination: Subscriber<R>,
9091
private predicate?: (value: T, index: number, source: Observable<T>) => boolean,
@@ -137,9 +138,12 @@ class FirstSubscriber<T, R> extends Subscriber<T> {
137138

138139
private _emitFinal(value: any) {
139140
const destination = this.destination;
140-
destination.next(value);
141-
destination.complete();
142-
this.hasCompleted = true;
141+
if (!this._emitted) {
142+
this._emitted = true;
143+
destination.next(value);
144+
destination.complete();
145+
this.hasCompleted = true;
146+
}
143147
}
144148

145149
protected _complete(): void {

0 commit comments

Comments
 (0)