21380fcf391f00f0c5cc69b63a0dfd954129e8422d7fba9c7db68edbe1cef587ab58602b0c2a1ae97b1655d774f17931c509bcae40ddb17fe2019c087cbe66 2.3 KB

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