MinBy.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 MinBy<TSource, TKey> : Producer<IList<TSource>>
  10. {
  11. private readonly IObservable<TSource> _source;
  12. private readonly Func<TSource, TKey> _keySelector;
  13. private readonly IComparer<TKey> _comparer;
  14. public MinBy(IObservable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
  15. {
  16. _source = source;
  17. _keySelector = keySelector;
  18. _comparer = comparer;
  19. }
  20. protected override IDisposable Run(IObserver<IList<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<IList<TSource>>, IObserver<TSource>
  27. {
  28. private readonly MinBy<TSource, TKey> _parent;
  29. private bool _hasValue;
  30. private TKey _lastKey;
  31. private List<TSource> _list;
  32. public _(MinBy<TSource, TKey> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
  33. : base(observer, cancel)
  34. {
  35. _parent = parent;
  36. _hasValue = false;
  37. _lastKey = default(TKey);
  38. _list = new List<TSource>();
  39. }
  40. public void OnNext(TSource value)
  41. {
  42. var key = default(TKey);
  43. try
  44. {
  45. key = _parent._keySelector(value);
  46. }
  47. catch (Exception ex)
  48. {
  49. base._observer.OnError(ex);
  50. base.Dispose();
  51. return;
  52. }
  53. var comparison = 0;
  54. if (!_hasValue)
  55. {
  56. _hasValue = true;
  57. _lastKey = key;
  58. }
  59. else
  60. {
  61. try
  62. {
  63. comparison = _parent._comparer.Compare(key, _lastKey);
  64. }
  65. catch (Exception ex)
  66. {
  67. base._observer.OnError(ex);
  68. base.Dispose();
  69. return;
  70. }
  71. }
  72. if (comparison < 0)
  73. {
  74. _lastKey = key;
  75. _list.Clear();
  76. }
  77. if (comparison <= 0)
  78. {
  79. _list.Add(value);
  80. }
  81. }
  82. public void OnError(Exception error)
  83. {
  84. base._observer.OnError(error);
  85. base.Dispose();
  86. }
  87. public void OnCompleted()
  88. {
  89. base._observer.OnNext(_list);
  90. base._observer.OnCompleted();
  91. base.Dispose();
  92. }
  93. }
  94. }
  95. }
  96. #endif