-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathstartWithTimeout.ts
48 lines (46 loc) · 1.13 KB
/
startWithTimeout.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/
import {
concat,
Observable,
OperatorFunction,
race,
SchedulerLike,
timer,
} from "rxjs";
import { mapTo, publish } from "rxjs/operators";
export function startWithTimeout<T, S = T>(
value: S,
duration: number | Date,
scheduler?: SchedulerLike
): OperatorFunction<T, S | T> {
if (duration === 0 && !scheduler) {
return (source) =>
new Observable<T | S>((subscriber) => {
let nexted = false;
const subscription = source.subscribe(
(value) => {
nexted = true;
subscriber.next(value);
},
subscriber.error.bind(subscriber),
subscriber.complete.bind(subscriber)
);
if (!nexted) {
subscriber.next(value);
}
return subscription;
});
}
return (source) =>
source.pipe(
publish((published) =>
race(
published,
concat(timer(duration, scheduler).pipe(mapTo(value)), published)
)
)
);
}