TimeInterval.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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, IClock clock)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. if (clock == null)
  14. throw new ArgumentNullException(nameof(clock));
  15. return Create<TimeInterval<TSource>>(observer => source.SubscribeSafeAsync(AsyncObserver.TimeInterval(observer, clock)));
  16. }
  17. }
  18. partial class AsyncObserver
  19. {
  20. public static IAsyncObserver<TSource> TimeInterval<TSource>(IAsyncObserver<TimeInterval<TSource>> observer, IClock clock)
  21. {
  22. if (observer == null)
  23. throw new ArgumentNullException(nameof(observer));
  24. if (clock == null)
  25. throw new ArgumentNullException(nameof(clock));
  26. var last = clock.Now;
  27. return Select<TSource, TimeInterval<TSource>>(observer, x =>
  28. {
  29. var now = clock.Now;
  30. var interval = now - last;
  31. last = now;
  32. return new TimeInterval<TSource>(x, interval);
  33. });
  34. }
  35. }
  36. }