MinBy.cs 3.2 KB

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