Debian Codegraph @

node/rxjs/src/internal/operators/timeInterval.ts

raw
1 import { asyncScheduler } from '../scheduler/async';
2 import { SchedulerLike, OperatorFunction } from '../types';
3 import { operate } from '../util/lift';
4 import { createOperatorSubscriber } from './OperatorSubscriber';
5
6 /**
7 * Emits an object containing the current value, and the time that has
8 * passed between emitting the current value and the previous value, which is
9 * calculated by using the provided `scheduler`'s `now()` method to retrieve
10 * the current time at each emission, then calculating the difference. The `scheduler`
11 * defaults to {@link asyncScheduler}, so by default, the `interval` will be in
12 * milliseconds.
13 *
14 * <span class="informal">Convert an Observable that emits items into one that
15 * emits indications of the amount of time elapsed between those emissions.</span>
16 *
17 * ![](timeInterval.png)
18 *
19 * ## Example
20 *
21 * Emit interval between current value with the last value
22 *
23 * ```ts
24 * import { interval, timeInterval } from 'rxjs';
25 *
26 * const seconds = interval(1000);
27 *
28 * seconds
29 * .pipe(timeInterval())
30 * .subscribe(value => console.log(value));
31 *
32 * // NOTE: The values will never be this precise,
33 * // intervals created with `interval` or `setInterval`
34 * // are non-deterministic.
35 *
36 * // { value: 0, interval: 1000 }
37 * // { value: 1, interval: 1000 }
38 * // { value: 2, interval: 1000 }
39 * ```
40 *
41 * @param scheduler Scheduler used to get the current time.
42 * @return A function that returns an Observable that emits information about
43 * value and interval.
44 */
45 export function timeInterval<T>(scheduler: SchedulerLike = asyncScheduler): OperatorFunction<T, TimeInterval<T>> {
46 return operate((source, subscriber) => {
47 let last = scheduler.now();
48 source.subscribe(
49 createOperatorSubscriber(subscriber, (value) => {
50 const now = scheduler.now();
51 const interval = now - last;
52 last = now;
53 subscriber.next(new TimeInterval(value, interval));
54 })
55 );
56 });
57 }
58
59 // TODO(benlesh): make this an interface, export the interface, but not the implemented class,
60 // there's no reason users should be manually creating this type.
61
62 export class TimeInterval<T> {
63 /**
64 * @deprecated Internal implementation detail, do not construct directly. Will be made an interface in v8.
65 */
66 constructor(public value: T, public interval: number) {}
67 }