TimeInterval.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System;
  4. using System.Diagnostics;
  5. using System.Reactive.Concurrency;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. namespace System.Reactive.Linq.Observαble
  9. {
  10. class TimeInterval<TSource> : Producer<System.Reactive.TimeInterval<TSource>>
  11. {
  12. private readonly IObservable<TSource> _source;
  13. private readonly IScheduler _scheduler;
  14. public TimeInterval(IObservable<TSource> source, IScheduler scheduler)
  15. {
  16. _source = source;
  17. _scheduler = scheduler;
  18. }
  19. protected override IDisposable Run(IObserver<System.Reactive.TimeInterval<TSource>> observer, IDisposable cancel, Action<IDisposable> setSink)
  20. {
  21. var sink = new _(this, observer, cancel);
  22. setSink(sink);
  23. return sink.Run();
  24. }
  25. class _ : Sink<System.Reactive.TimeInterval<TSource>>, IObserver<TSource>
  26. {
  27. private readonly TimeInterval<TSource> _parent;
  28. public _(TimeInterval<TSource> parent, IObserver<System.Reactive.TimeInterval<TSource>> observer, IDisposable cancel)
  29. : base(observer, cancel)
  30. {
  31. _parent = parent;
  32. }
  33. private IStopwatch _watch;
  34. private TimeSpan _last;
  35. public IDisposable Run()
  36. {
  37. _watch = _parent._scheduler.StartStopwatch();
  38. _last = TimeSpan.Zero;
  39. return _parent._source.Subscribe(this);
  40. }
  41. public void OnNext(TSource value)
  42. {
  43. var now = _watch.Elapsed;
  44. var span = now.Subtract(_last);
  45. _last = now;
  46. base._observer.OnNext(new System.Reactive.TimeInterval<TSource>(value, span));
  47. }
  48. public void OnError(Exception error)
  49. {
  50. base._observer.OnError(error);
  51. Dispose();
  52. }
  53. public void OnCompleted()
  54. {
  55. base._observer.OnCompleted();
  56. Dispose();
  57. }
  58. }
  59. }
  60. }
  61. #endif