Any.cs 3.2 KB

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