Range.cs 2.4 KB

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