Skip to content

Commit 4ce4433

Browse files
committed
fix(bufferTime): handle closing context when synchronously unsubscribed
closes #1763
1 parent 0a6c4e8 commit 4ce4433

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

spec/operators/bufferTime-spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,20 @@ describe('Observable.prototype.bufferTime', () => {
284284
expectObservable(result).toBe(expected, values);
285285
expectSubscriptions(e1.subscriptions).toBe(e1subs);
286286
});
287+
288+
it('should not throw when subscription synchronously unsubscribed after emit', () => {
289+
const e1 = hot('---a---b---c---d---e---f---g-----|');
290+
const subs = '^ !';
291+
const t = time( '----------|');
292+
const expected = '----------w---------(x|)';
293+
const values = {
294+
w: ['a', 'b'],
295+
x: ['c', 'd', 'e']
296+
};
297+
298+
const result = e1.bufferTime(t, null, Number.POSITIVE_INFINITY, rxTestScheduler).take(2);
299+
300+
expectObservable(result).toBe(expected, values);
301+
expectSubscriptions(e1.subscriptions).toBe(subs);
302+
});
287303
});

src/operator/bufferTime.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,15 +183,19 @@ class BufferTimeSubscriber<T> extends Subscriber<T> {
183183
}
184184

185185
openContext(): Context<T> {
186-
let context: Context<T> = new Context<T>();
186+
const context: Context<T> = new Context<T>();
187187
this.contexts.push(context);
188188
return context;
189189
}
190190

191191
closeContext(context: Context<T>) {
192192
this.destination.next(context.buffer);
193193
const contexts = this.contexts;
194-
contexts.splice(contexts.indexOf(context), 1);
194+
195+
const spliceIndex = contexts ? contexts.indexOf(context) : -1;
196+
if (spliceIndex >= 0) {
197+
contexts.splice(contexts.indexOf(context), 1);
198+
}
195199
}
196200
}
197201

@@ -203,8 +207,8 @@ function dispatchBufferTimeSpanOnly(state: any) {
203207
subscriber.closeContext(prevContext);
204208
}
205209

206-
state.context = subscriber.openContext();
207210
if (!subscriber.isUnsubscribed) {
211+
state.context = subscriber.openContext();
208212
state.context.closeAction = (<any>this).schedule(state, state.bufferTimeSpan);
209213
}
210214
}

0 commit comments

Comments
 (0)