Contains.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.Collections.Generic;
  5. namespace System.Reactive.Linq.ObservableImpl
  6. {
  7. internal sealed class Contains<TSource> : Producer<bool>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. private readonly TSource _value;
  11. private readonly IEqualityComparer<TSource> _comparer;
  12. public Contains(IObservable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
  13. {
  14. _source = source;
  15. _value = value;
  16. _comparer = comparer;
  17. }
  18. protected override IDisposable Run(IObserver<bool> observer, IDisposable cancel, Action<IDisposable> setSink)
  19. {
  20. var sink = new _(this, observer, cancel);
  21. setSink(sink);
  22. return _source.SubscribeSafe(sink);
  23. }
  24. private sealed class _ : Sink<bool>, IObserver<TSource>
  25. {
  26. // CONSIDER: This sink has a parent reference that can be considered for removal.
  27. private readonly Contains<TSource> _parent;
  28. public _(Contains<TSource> parent, IObserver<bool> observer, IDisposable cancel)
  29. : base(observer, cancel)
  30. {
  31. _parent = parent;
  32. }
  33. public void OnNext(TSource value)
  34. {
  35. var res = false;
  36. try
  37. {
  38. res = _parent._comparer.Equals(value, _parent._value);
  39. }
  40. catch (Exception ex)
  41. {
  42. base._observer.OnError(ex);
  43. base.Dispose();
  44. return;
  45. }
  46. if (res)
  47. {
  48. base._observer.OnNext(true);
  49. base._observer.OnCompleted();
  50. base.Dispose();
  51. }
  52. }
  53. public void OnError(Exception error)
  54. {
  55. base._observer.OnError(error);
  56. base.Dispose();
  57. }
  58. public void OnCompleted()
  59. {
  60. base._observer.OnNext(false);
  61. base._observer.OnCompleted();
  62. base.Dispose();
  63. }
  64. }
  65. }
  66. }