Contains.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. using System.Collections.Generic;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. class Contains<TSource> : Producer<bool>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly TSource _value;
  12. private readonly IEqualityComparer<TSource> _comparer;
  13. public Contains(IObservable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
  14. {
  15. _source = source;
  16. _value = value;
  17. _comparer = comparer;
  18. }
  19. protected override IDisposable Run(IObserver<bool> observer, IDisposable cancel, Action<IDisposable> setSink)
  20. {
  21. var sink = new _(this, observer, cancel);
  22. setSink(sink);
  23. return _source.SubscribeSafe(sink);
  24. }
  25. class _ : Sink<bool>, IObserver<TSource>
  26. {
  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. }