TimeInterval.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 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. 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<TimeInterval<TSource>>(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<TimeInterval<TSource>>(observer => source.SubscribeSafeAsync(AsyncObserver.TimeInterval(observer, clock)));
  22. }
  23. }
  24. partial class AsyncObserver
  25. {
  26. public static IAsyncObserver<TSource> TimeInterval<TSource>(IAsyncObserver<TimeInterval<TSource>> observer)
  27. {
  28. if (observer == null)
  29. throw new ArgumentNullException(nameof(observer));
  30. return TimeInterval(observer, Clock.Default);
  31. }
  32. public static IAsyncObserver<TSource> TimeInterval<TSource>(IAsyncObserver<TimeInterval<TSource>> observer, IClock clock)
  33. {
  34. if (observer == null)
  35. throw new ArgumentNullException(nameof(observer));
  36. if (clock == null)
  37. throw new ArgumentNullException(nameof(clock));
  38. var last = clock.Now;
  39. return Select<TSource, TimeInterval<TSource>>(observer, x =>
  40. {
  41. var now = clock.Now;
  42. var interval = now - last;
  43. last = now;
  44. return new TimeInterval<TSource>(x, interval);
  45. });
  46. }
  47. }
  48. }