Last active
November 12, 2023 19:23
-
-
Save wyrfel/28c65228fcf527a56238bd9b7f860dd5 to your computer and use it in GitHub Desktop.
RxJS timer() replacement for values more than 24 days in the future
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// compare https://github.com/ReactiveX/rxjs/issues/3015 | |
import { concat, last, Observable, repeat, scan, SchedulerLike, take, timer } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
const MAX_INT = 2147483647; | |
const getTimer = (time: number, scheduler: SchedulerLike | undefined): Observable<0> => { | |
if (time > MAX_INT) { | |
const n: number = Math.floor(time / MAX_INT); | |
const r: number = time % MAX_INT; | |
return concat(timer(MAX_INT, MAX_INT, scheduler).pipe(take(n)), timer(r, scheduler)).pipe( | |
last(), | |
map(() => 0) | |
); | |
} | |
return timer(time, scheduler); | |
}; | |
const isInterval = (interval: SchedulerLike | number | undefined): interval is number => typeof interval === 'number'; | |
export const longTimer = ( | |
time: number | Date, | |
interval?: SchedulerLike | number, | |
scheduler?: SchedulerLike | |
): Observable<number> => { | |
if (time instanceof Date) { | |
time = time.getTime() - new Date().getTime(); | |
} | |
if (!isInterval(interval)) { | |
return getTimer(time, interval); | |
} | |
return concat( | |
getTimer(time, scheduler), | |
getTimer(interval, scheduler).pipe( | |
repeat(), | |
scan((acc) => acc + 1, 0) | |
) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment