DistinctUntilChanged.cs 2.5 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 DistinctUntilChanged<TSource, TKey> : Producer<TSource, DistinctUntilChanged<TSource, TKey>._>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. private readonly Func<TSource, TKey> _keySelector;
  11. private readonly IEqualityComparer<TKey> _comparer;
  12. public DistinctUntilChanged(IObservable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  13. {
  14. _source = source;
  15. _keySelector = keySelector;
  16. _comparer = comparer;
  17. }
  18. protected override _ CreateSink(IObserver<TSource> observer) => new _(this, observer);
  19. protected override void Run(_ sink) => sink.Run(_source);
  20. internal sealed class _ : IdentitySink<TSource>
  21. {
  22. private readonly Func<TSource, TKey> _keySelector;
  23. private readonly IEqualityComparer<TKey> _comparer;
  24. private TKey _currentKey;
  25. private bool _hasCurrentKey;
  26. public _(DistinctUntilChanged<TSource, TKey> parent, IObserver<TSource> observer)
  27. : base(observer)
  28. {
  29. _keySelector = parent._keySelector;
  30. _comparer = parent._comparer;
  31. }
  32. public override void OnNext(TSource value)
  33. {
  34. TKey key;
  35. try
  36. {
  37. key = _keySelector(value);
  38. }
  39. catch (Exception exception)
  40. {
  41. ForwardOnError(exception);
  42. return;
  43. }
  44. var comparerEquals = false;
  45. if (_hasCurrentKey)
  46. {
  47. try
  48. {
  49. comparerEquals = _comparer.Equals(_currentKey, key);
  50. }
  51. catch (Exception exception)
  52. {
  53. ForwardOnError(exception);
  54. return;
  55. }
  56. }
  57. if (!_hasCurrentKey || !comparerEquals)
  58. {
  59. _hasCurrentKey = true;
  60. _currentKey = key;
  61. ForwardOnNext(value);
  62. }
  63. }
  64. }
  65. }
  66. }