Contains.cs 2.3 KB

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