Skip to content

Commit

Permalink
fix(timeout): no longer will timeout when receiving the first value s…
Browse files Browse the repository at this point in the history
…ynchronously (#6865)

* fix(timeout): do not timeout if source emits synchronously when subscribed

Closes #6862

* chore: Improve comments

* chore: minor test cleanup

* chore: minor test cleanup

* chore: Fix broken test that I broke! lol

Co-authored-by: Ben Lesh <ben@benlesh.com>
  • Loading branch information
danielwiehl and benlesh committed Mar 8, 2022
1 parent 45a22e2 commit 2330c96
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 11 additions & 2 deletions spec/operators/timeout-spec.ts
@@ -1,8 +1,8 @@
/** @prettier */
import { expect } from 'chai';
import { timeout, mergeMap, take } from 'rxjs/operators';
import { timeout, mergeMap, take, concatWith } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { TimeoutError, of, Observable } from 'rxjs';
import { TimeoutError, of, Observable, NEVER } from 'rxjs';
import { observableMatcher } from '../helpers/observableMatcher';

/** @test {timeout} */
Expand Down Expand Up @@ -691,6 +691,15 @@ describe('timeout operator', () => {
expectSubscriptions(inner.subscriptions).toBe([]);
});
});

it('should not timeout if source emits synchronously when subscribed', () => {
rxTestScheduler.run(({ expectObservable, time }) => {
const source = of('a').pipe(concatWith(NEVER));
const t = time(' ---|');
const expected = 'a---';
expectObservable(source.pipe(timeout({ first: new Date(t) }))).toBe(expected);
});
});
});

it('should stop listening to a synchronous observable when unsubscribed', () => {
Expand Down
4 changes: 3 additions & 1 deletion src/internal/operators/timeout.ts
Expand Up @@ -386,10 +386,12 @@ export function timeout<T, O extends ObservableInput<any>, M>(
);

// Intentionally terse code.
// If we've `seen` a value, that means the "first" clause was met already, if it existed.
// it also means that a timer was already started for "each" (in the next handler above).
// If `first` was provided, and it's a number, then use it.
// If `first` was provided and it's not a number, it's a Date, and we get the difference between it and "now".
// If `first` was not provided at all, then our first timer will be the value from `each`.
startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler!.now()) : each!);
!seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler!.now()) : each!);
});
}

Expand Down

0 comments on commit 2330c96

Please sign in to comment.