1
0

Range.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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;
  5. using System.Reactive.Concurrency;
  6. using System.Reactive.Disposables;
  7. namespace System.Reactive.Linq.ObservableImpl
  8. {
  9. class Range : Producer<int>
  10. {
  11. private readonly int _start;
  12. private readonly int _count;
  13. private readonly IScheduler _scheduler;
  14. public Range(int start, int count, IScheduler scheduler)
  15. {
  16. _start = start;
  17. _count = count;
  18. _scheduler = scheduler;
  19. }
  20. protected override IDisposable Run(IObserver<int> observer, IDisposable cancel, Action<IDisposable> setSink)
  21. {
  22. var sink = new _(this, observer, cancel);
  23. setSink(sink);
  24. return sink.Run();
  25. }
  26. class _ : Sink<int>
  27. {
  28. private readonly Range _parent;
  29. public _(Range parent, IObserver<int> observer, IDisposable cancel)
  30. : base(observer, cancel)
  31. {
  32. _parent = parent;
  33. }
  34. public IDisposable Run()
  35. {
  36. var longRunning = _parent._scheduler.AsLongRunning();
  37. if (longRunning != null)
  38. {
  39. return longRunning.ScheduleLongRunning(0, Loop);
  40. }
  41. else
  42. {
  43. return _parent._scheduler.Schedule(0, LoopRec);
  44. }
  45. }
  46. private void Loop(int i, ICancelable cancel)
  47. {
  48. while (!cancel.IsDisposed && i < _parent._count)
  49. {
  50. base._observer.OnNext(_parent._start + i);
  51. i++;
  52. }
  53. if (!cancel.IsDisposed)
  54. base._observer.OnCompleted();
  55. base.Dispose();
  56. }
  57. private void LoopRec(int i, Action<int> recurse)
  58. {
  59. if (i < _parent._count)
  60. {
  61. base._observer.OnNext(_parent._start + i);
  62. recurse(i + 1);
  63. }
  64. else
  65. {
  66. base._observer.OnCompleted();
  67. base.Dispose();
  68. }
  69. }
  70. }
  71. }
  72. }