TimeInterval.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Concurrency;
  5. namespace System.Reactive.Linq
  6. {
  7. public partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<TimeInterval<TSource>> TimeInterval<TSource>(this IAsyncObservable<TSource> source)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return Create<TSource, TimeInterval<TSource>>(source, static (source, observer) => source.SubscribeSafeAsync(AsyncObserver.TimeInterval(observer)));
  14. }
  15. public static IAsyncObservable<TimeInterval<TSource>> TimeInterval<TSource>(this IAsyncObservable<TSource> source, IClock clock)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. if (clock == null)
  20. throw new ArgumentNullException(nameof(clock));
  21. return Create(
  22. source,
  23. clock,
  24. default(TimeInterval<TSource>),
  25. (source, clock, observer) => source.SubscribeSafeAsync(AsyncObserver.TimeInterval(observer, clock))); ;
  26. }
  27. }
  28. public partial class AsyncObserver
  29. {
  30. public static IAsyncObserver<TSource> TimeInterval<TSource>(IAsyncObserver<TimeInterval<TSource>> observer)
  31. {
  32. if (observer == null)
  33. throw new ArgumentNullException(nameof(observer));
  34. return TimeInterval(observer, Clock.Default);
  35. }
  36. public static IAsyncObserver<TSource> TimeInterval<TSource>(IAsyncObserver<TimeInterval<TSource>> observer, IClock clock)
  37. {
  38. if (observer == null)
  39. throw new ArgumentNullException(nameof(observer));
  40. if (clock == null)
  41. throw new ArgumentNullException(nameof(clock));
  42. var last = clock.Now;
  43. return Select<TSource, TimeInterval<TSource>>(observer, x =>
  44. {
  45. var now = clock.Now;
  46. var interval = now - last;
  47. last = now;
  48. return new TimeInterval<TSource>(x, interval);
  49. });
  50. }
  51. }
  52. }