All.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. internal sealed class All<TSource> : Producer<bool, All<TSource>._>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. private readonly Func<TSource, bool> _predicate;
  10. public All(IObservable<TSource> source, Func<TSource, bool> predicate)
  11. {
  12. _source = source;
  13. _predicate = predicate;
  14. }
  15. protected override _ CreateSink(IObserver<bool> observer, IDisposable cancel) => new _(_predicate, observer, cancel);
  16. protected override IDisposable Run(_ sink) => _source.SubscribeSafe(sink);
  17. internal sealed class _ : Sink<bool>, IObserver<TSource>
  18. {
  19. private readonly Func<TSource, bool> _predicate;
  20. public _(Func<TSource, bool> predicate, IObserver<bool> observer, IDisposable cancel)
  21. : base(observer, cancel)
  22. {
  23. _predicate = predicate;
  24. }
  25. public void OnNext(TSource value)
  26. {
  27. var res = false;
  28. try
  29. {
  30. res = _predicate(value);
  31. }
  32. catch (Exception ex)
  33. {
  34. base._observer.OnError(ex);
  35. base.Dispose();
  36. return;
  37. }
  38. if (!res)
  39. {
  40. base._observer.OnNext(false);
  41. base._observer.OnCompleted();
  42. base.Dispose();
  43. }
  44. }
  45. public void OnError(Exception error)
  46. {
  47. base._observer.OnError(error);
  48. base.Dispose();
  49. }
  50. public void OnCompleted()
  51. {
  52. base._observer.OnNext(true);
  53. base._observer.OnCompleted();
  54. base.Dispose();
  55. }
  56. }
  57. }
  58. }