Contains.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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, Contains<TSource>._>
  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 _ CreateSink(IObserver<bool> observer) => new _(this, observer);
  19. protected override void Run(_ sink) => sink.Run(_source);
  20. internal sealed class _ : Sink<TSource, bool>
  21. {
  22. private readonly TSource _value;
  23. private readonly IEqualityComparer<TSource> _comparer;
  24. public _(Contains<TSource> parent, IObserver<bool> observer)
  25. : base(observer)
  26. {
  27. _value = parent._value;
  28. _comparer = parent._comparer;
  29. }
  30. public override void OnNext(TSource value)
  31. {
  32. bool res;
  33. try
  34. {
  35. res = _comparer.Equals(value, _value);
  36. }
  37. catch (Exception ex)
  38. {
  39. ForwardOnError(ex);
  40. return;
  41. }
  42. if (res)
  43. {
  44. ForwardOnNext(true);
  45. ForwardOnCompleted();
  46. }
  47. }
  48. public override void OnCompleted()
  49. {
  50. ForwardOnNext(false);
  51. ForwardOnCompleted();
  52. }
  53. }
  54. }
  55. }