DistinctUntilChanged.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 DistinctUntilChanged<TSource, TKey> : Producer<TSource>
  10. {
  11. private readonly IObservable<TSource> _source;
  12. private readonly Func<TSource, TKey> _keySelector;
  13. private readonly IEqualityComparer<TKey> _comparer;
  14. public DistinctUntilChanged(IObservable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  15. {
  16. _source = source;
  17. _keySelector = keySelector;
  18. _comparer = comparer;
  19. }
  20. protected override IDisposable Run(IObserver<TSource> 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<TSource>, IObserver<TSource>
  27. {
  28. private readonly DistinctUntilChanged<TSource, TKey> _parent;
  29. private TKey _currentKey;
  30. private bool _hasCurrentKey;
  31. public _(DistinctUntilChanged<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  32. : base(observer, cancel)
  33. {
  34. _parent = parent;
  35. _currentKey = default(TKey);
  36. _hasCurrentKey = false;
  37. }
  38. public void OnNext(TSource value)
  39. {
  40. var key = default(TKey);
  41. try
  42. {
  43. key = _parent._keySelector(value);
  44. }
  45. catch (Exception exception)
  46. {
  47. base._observer.OnError(exception);
  48. base.Dispose();
  49. return;
  50. }
  51. var comparerEquals = false;
  52. if (_hasCurrentKey)
  53. {
  54. try
  55. {
  56. comparerEquals = _parent._comparer.Equals(_currentKey, key);
  57. }
  58. catch (Exception exception)
  59. {
  60. base._observer.OnError(exception);
  61. base.Dispose();
  62. return;
  63. }
  64. }
  65. if (!_hasCurrentKey || !comparerEquals)
  66. {
  67. _hasCurrentKey = true;
  68. _currentKey = key;
  69. base._observer.OnNext(value);
  70. }
  71. }
  72. public void OnError(Exception error)
  73. {
  74. base._observer.OnError(error);
  75. base.Dispose();
  76. }
  77. public void OnCompleted()
  78. {
  79. base._observer.OnCompleted();
  80. base.Dispose();
  81. }
  82. }
  83. }
  84. }
  85. #endif