Any.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. class Any<TSource> : Producer<bool>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly Func<TSource, bool> _predicate;
  12. public Any(IObservable<TSource> source)
  13. {
  14. _source = source;
  15. }
  16. public Any(IObservable<TSource> source, Func<TSource, bool> predicate)
  17. {
  18. _source = source;
  19. _predicate = predicate;
  20. }
  21. protected override IDisposable Run(IObserver<bool> observer, IDisposable cancel, Action<IDisposable> setSink)
  22. {
  23. if (_predicate != null)
  24. {
  25. var sink = new AnyImpl(this, observer, cancel);
  26. setSink(sink);
  27. return _source.SubscribeSafe(sink);
  28. }
  29. else
  30. {
  31. var sink = new _(observer, cancel);
  32. setSink(sink);
  33. return _source.SubscribeSafe(sink);
  34. }
  35. }
  36. class _ : Sink<bool>, IObserver<TSource>
  37. {
  38. public _(IObserver<bool> observer, IDisposable cancel)
  39. : base(observer, cancel)
  40. {
  41. }
  42. public void OnNext(TSource value)
  43. {
  44. base._observer.OnNext(true);
  45. base._observer.OnCompleted();
  46. base.Dispose();
  47. }
  48. public void OnError(Exception error)
  49. {
  50. base._observer.OnError(error);
  51. base.Dispose();
  52. }
  53. public void OnCompleted()
  54. {
  55. base._observer.OnNext(false);
  56. base._observer.OnCompleted();
  57. base.Dispose();
  58. }
  59. }
  60. class AnyImpl : Sink<bool>, IObserver<TSource>
  61. {
  62. private readonly Any<TSource> _parent;
  63. public AnyImpl(Any<TSource> parent, IObserver<bool> observer, IDisposable cancel)
  64. : base(observer, cancel)
  65. {
  66. _parent = parent;
  67. }
  68. public void OnNext(TSource value)
  69. {
  70. var res = false;
  71. try
  72. {
  73. res = _parent._predicate(value);
  74. }
  75. catch (Exception ex)
  76. {
  77. base._observer.OnError(ex);
  78. base.Dispose();
  79. return;
  80. }
  81. if (res)
  82. {
  83. base._observer.OnNext(true);
  84. base._observer.OnCompleted();
  85. base.Dispose();
  86. }
  87. }
  88. public void OnError(Exception error)
  89. {
  90. base._observer.OnError(error);
  91. base.Dispose();
  92. }
  93. public void OnCompleted()
  94. {
  95. base._observer.OnNext(false);
  96. base._observer.OnCompleted();
  97. base.Dispose();
  98. }
  99. }
  100. }
  101. }
  102. #endif