While.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #if !NO_PERF
  5. using System;
  6. using System.Collections.Generic;
  7. namespace System.Reactive.Linq.ObservableImpl
  8. {
  9. class While<TSource> : Producer<TSource>, IConcatenatable<TSource>
  10. {
  11. private readonly Func<bool> _condition;
  12. private readonly IObservable<TSource> _source;
  13. public While(Func<bool> condition, IObservable<TSource> source)
  14. {
  15. _condition = condition;
  16. _source = source;
  17. }
  18. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  19. {
  20. var sink = new _(observer, cancel);
  21. setSink(sink);
  22. return sink.Run(GetSources());
  23. }
  24. public IEnumerable<IObservable<TSource>> GetSources()
  25. {
  26. while (_condition())
  27. yield return _source;
  28. }
  29. class _ : ConcatSink<TSource>
  30. {
  31. public _(IObserver<TSource> observer, IDisposable cancel)
  32. : base(observer, cancel)
  33. {
  34. }
  35. public override void OnNext(TSource value)
  36. {
  37. base._observer.OnNext(value);
  38. }
  39. public override void OnError(Exception error)
  40. {
  41. base._observer.OnError(error);
  42. base.Dispose();
  43. }
  44. }
  45. }
  46. }
  47. #endif