Any.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. internal static class Any<TSource>
  7. {
  8. internal sealed class Count : Producer<bool, Count._>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. public Count(IObservable<TSource> source)
  12. {
  13. _source = source;
  14. }
  15. protected override _ CreateSink(IObserver<bool> observer) => new _(observer);
  16. protected override void Run(_ sink) => sink.Run(_source);
  17. internal sealed class _ : Sink<TSource, bool>
  18. {
  19. public _(IObserver<bool> observer)
  20. : base(observer)
  21. {
  22. }
  23. public override void OnNext(TSource value)
  24. {
  25. ForwardOnNext(true);
  26. ForwardOnCompleted();
  27. }
  28. public override void OnCompleted()
  29. {
  30. ForwardOnNext(false);
  31. ForwardOnCompleted();
  32. }
  33. }
  34. }
  35. internal sealed class Predicate : Producer<bool, Predicate._>
  36. {
  37. private readonly IObservable<TSource> _source;
  38. private readonly Func<TSource, bool> _predicate;
  39. public Predicate(IObservable<TSource> source, Func<TSource, bool> predicate)
  40. {
  41. _source = source;
  42. _predicate = predicate;
  43. }
  44. protected override _ CreateSink(IObserver<bool> observer) => new _(_predicate, observer);
  45. protected override void Run(_ sink) => sink.Run(_source);
  46. internal sealed class _ : Sink<TSource, bool>
  47. {
  48. private readonly Func<TSource, bool> _predicate;
  49. public _(Func<TSource, bool> predicate, IObserver<bool> observer)
  50. : base(observer)
  51. {
  52. _predicate = predicate;
  53. }
  54. public override void OnNext(TSource value)
  55. {
  56. bool res;
  57. try
  58. {
  59. res = _predicate(value);
  60. }
  61. catch (Exception ex)
  62. {
  63. ForwardOnError(ex);
  64. return;
  65. }
  66. if (res)
  67. {
  68. ForwardOnNext(true);
  69. ForwardOnCompleted();
  70. }
  71. }
  72. public override void OnCompleted()
  73. {
  74. ForwardOnNext(false);
  75. ForwardOnCompleted();
  76. }
  77. }
  78. }
  79. }
  80. }