Distinct.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 Distinct<TSource, TKey> : Producer<TSource>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. private readonly Func<TSource, TKey> _keySelector;
  11. private readonly IEqualityComparer<TKey> _comparer;
  12. public Distinct(IObservable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  13. {
  14. _source = source;
  15. _keySelector = keySelector;
  16. _comparer = comparer;
  17. }
  18. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  19. {
  20. var sink = new _(this, observer, cancel);
  21. setSink(sink);
  22. return _source.SubscribeSafe(sink);
  23. }
  24. class _ : Sink<TSource>, IObserver<TSource>
  25. {
  26. private readonly Distinct<TSource, TKey> _parent;
  27. private HashSet<TKey> _hashSet;
  28. public _(Distinct<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  29. : base(observer, cancel)
  30. {
  31. _parent = parent;
  32. _hashSet = new HashSet<TKey>(_parent._comparer);
  33. }
  34. public void OnNext(TSource value)
  35. {
  36. var key = default(TKey);
  37. var hasAdded = false;
  38. try
  39. {
  40. key = _parent._keySelector(value);
  41. hasAdded = _hashSet.Add(key);
  42. }
  43. catch (Exception exception)
  44. {
  45. base._observer.OnError(exception);
  46. base.Dispose();
  47. return;
  48. }
  49. if (hasAdded)
  50. base._observer.OnNext(value);
  51. }
  52. public void OnError(Exception error)
  53. {
  54. base._observer.OnError(error);
  55. base.Dispose();
  56. }
  57. public void OnCompleted()
  58. {
  59. base._observer.OnCompleted();
  60. base.Dispose();
  61. }
  62. }
  63. }
  64. }