51e23c04fc4e40740f9f3ce58dc49b52eff2a6308eed0518cd03deffc6d26e6785f789cf58115bae79a9db3767a9283c84059e981847d84296ff306e44b4b2 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { asyncScheduler } from '../scheduler/async';
  2. import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
  3. import { sample } from './sample';
  4. import { interval } from '../observable/interval';
  5. /**
  6. * Emits the most recently emitted value from the source Observable within
  7. * periodic time intervals.
  8. *
  9. * <span class="informal">Samples the source Observable at periodic time
  10. * intervals, emitting what it samples.</span>
  11. *
  12. * ![](sampleTime.png)
  13. *
  14. * `sampleTime` periodically looks at the source Observable and emits whichever
  15. * value it has most recently emitted since the previous sampling, unless the
  16. * source has not emitted anything since the previous sampling. The sampling
  17. * happens periodically in time every `period` milliseconds (or the time unit
  18. * defined by the optional `scheduler` argument). The sampling starts as soon as
  19. * the output Observable is subscribed.
  20. *
  21. * ## Example
  22. *
  23. * Every second, emit the most recent click at most once
  24. *
  25. * ```ts
  26. * import { fromEvent, sampleTime } from 'rxjs';
  27. *
  28. * const clicks = fromEvent(document, 'click');
  29. * const result = clicks.pipe(sampleTime(1000));
  30. *
  31. * result.subscribe(x => console.log(x));
  32. * ```
  33. *
  34. * @see {@link auditTime}
  35. * @see {@link debounceTime}
  36. * @see {@link delay}
  37. * @see {@link sample}
  38. * @see {@link throttleTime}
  39. *
  40. * @param period The sampling period expressed in milliseconds or the time unit
  41. * determined internally by the optional `scheduler`.
  42. * @param scheduler The {@link SchedulerLike} to use for managing the timers
  43. * that handle the sampling.
  44. * @return A function that returns an Observable that emits the results of
  45. * sampling the values emitted by the source Observable at the specified time
  46. * interval.
  47. */
  48. export function sampleTime<T>(period: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {
  49. return sample(interval(period, scheduler));
  50. }