Skip to content

Commit

Permalink
fix(debounceTime): unschedule dangling task on unsubscribe before com…
Browse files Browse the repository at this point in the history
…plete (#6464)
  • Loading branch information
backbone87 committed Jul 5, 2021
1 parent 0da9f44 commit 7ab0a4c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
25 changes: 22 additions & 3 deletions spec/operators/debounceTime-spec.ts
@@ -1,10 +1,12 @@
/** @prettier */
import { expect } from 'chai';
import { of, Subject } from 'rxjs';
import { debounceTime, mergeMap } from 'rxjs/operators';
import { NEVER, of, Subject } from 'rxjs';
import { AnimationFrameAction } from 'rxjs/internal/scheduler/AnimationFrameAction';
import { AnimationFrameScheduler } from 'rxjs/internal/scheduler/AnimationFrameScheduler';
import { debounceTime, mergeMap, startWith } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { observableMatcher } from '../helpers/observableMatcher';
import { VirtualTimeScheduler } from '../../src/internal/scheduler/VirtualTimeScheduler';
import { observableMatcher } from '../helpers/observableMatcher';

/** @test {debounceTime} */
describe('debounceTime', () => {
Expand Down Expand Up @@ -221,4 +223,21 @@ describe('debounceTime', () => {

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

it('should unsubscribe from the scheduled debounce action when downstream unsubscribes', () => {
const scheduler = new AnimationFrameScheduler(AnimationFrameAction);

expect(scheduler._scheduled).to.not.exist;
expect(scheduler.actions).to.be.empty;

const subscription = NEVER.pipe(startWith(1), debounceTime(0, scheduler)).subscribe();

expect(scheduler._scheduled).to.exist;
expect(scheduler.actions.length).to.equal(1);

subscription.unsubscribe();

expect(scheduler._scheduled).to.not.exist;
expect(scheduler.actions).to.be.empty;
});
});
2 changes: 2 additions & 0 deletions src/internal/operators/debounceTime.ts
Expand Up @@ -86,6 +86,7 @@ export function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = asyn
if (now < targetTime) {
// On that case, re-schedule to the new target
activeTask = this.schedule(undefined, targetTime - now);
subscriber.add(activeTask);
return;
}

Expand All @@ -102,6 +103,7 @@ export function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = asyn
// Only set up a task if it's not already up
if (!activeTask) {
activeTask = scheduler.schedule(emitWhenIdle, dueTime);
subscriber.add(activeTask);
}
},
() => {
Expand Down

0 comments on commit 7ab0a4c

Please sign in to comment.