Skip to content

Commit

Permalink
fix(throttle): no longer emits more than necessary in sync/sync trail…
Browse files Browse the repository at this point in the history
…ing case (#6059)

Resolves an edge case where if a user provided a synchronous source and a synchronous notifier, using a trailing behavior, the returned observable would get caught in a loop emitting the final value over and over again.

fixes: #6058
  • Loading branch information
benlesh authored Feb 26, 2021
1 parent 5bc8e33 commit 9da638a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
16 changes: 15 additions & 1 deletion spec/operators/throttle-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { throttle, mergeMap, mapTo, take } from 'rxjs/operators';
import { of, concat, timer, Observable } from 'rxjs';

/** @test {throttle} */
describe('throttle operator', () => {
describe('throttle', () => {
it('should immediately emit the first value in each time window', () => {
const e1 = hot('-a-xy-----b--x--cxxx-|');
const e1subs = '^ !';
Expand All @@ -21,6 +21,20 @@ describe('throttle operator', () => {
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});

it('should handle sync source with sync notifier and trailing appropriately', () => {
let results: any[] = [];
const source = of(1).pipe(
throttle(() => of(1), { leading: false, trailing: true })
);

source.subscribe({
next: value => results.push(value),
complete: () => results.push('done')
});

expect(results).to.deep.equal([1, 'done'])
});

it('should simply mirror the source if values are not emitted often enough', () => {
const e1 = hot('-a--------b-----c----|');
const e1subs = '^ !';
Expand Down
13 changes: 9 additions & 4 deletions src/internal/operators/throttle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,16 @@ export function throttle<T>(

const send = () => {
if (hasValue) {
subscriber.next(sendValue!);
!isComplete && startThrottle(sendValue!);
// Ensure we clear out our value and hasValue flag
// before we emit, otherwise reentrant code can cause
// issues here.
hasValue = false;
const value = sendValue!;
sendValue = null;
// Emit the value.
subscriber.next(value);
!isComplete && startThrottle(value);
}
hasValue = false;
sendValue = null;
};

source.subscribe(
Expand Down

0 comments on commit 9da638a

Please sign in to comment.