1
0

Range.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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, Range._>
  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 _ CreateSink(IObserver<int> observer) => new _(this, observer);
  20. protected override void Run(_ sink) => sink.Run(_scheduler);
  21. internal sealed class _ : IdentitySink<int>
  22. {
  23. private readonly int _start;
  24. private readonly int _count;
  25. public _(Range parent, IObserver<int> observer)
  26. : base(observer)
  27. {
  28. _start = parent._start;
  29. _count = parent._count;
  30. }
  31. public void Run(IScheduler scheduler)
  32. {
  33. var longRunning = scheduler.AsLongRunning();
  34. if (longRunning != null)
  35. {
  36. SetUpstream(longRunning.ScheduleLongRunning(0, Loop));
  37. }
  38. else
  39. {
  40. SetUpstream(scheduler.Schedule(0, LoopRec));
  41. }
  42. }
  43. private void Loop(int i, ICancelable cancel)
  44. {
  45. while (!cancel.IsDisposed && i < _count)
  46. {
  47. ForwardOnNext(_start + i);
  48. i++;
  49. }
  50. if (!cancel.IsDisposed)
  51. ForwardOnCompleted();
  52. }
  53. private void LoopRec(int i, Action<int> recurse)
  54. {
  55. if (i < _count)
  56. {
  57. ForwardOnNext(_start + i);
  58. recurse(i + 1);
  59. }
  60. else
  61. {
  62. ForwardOnCompleted();
  63. }
  64. }
  65. }
  66. }
  67. }