Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/MinBy.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 #if !NO_PERF
4 using System;
5 using System.Collections.Generic;
6
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
15 public MinBy(IObservable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
16 {
17 _source = source;
18 _keySelector = keySelector;
19 _comparer = comparer;
20 }
21
22 protected override IDisposable Run(IObserver<IList<TSource>> observer, IDisposable cancel, Action<IDisposable> setSink)
23 {
24 var sink = new _(this, observer, cancel);
25 setSink(sink);
26 return _source.SubscribeSafe(sink);
27 }
28
29 class _ : Sink<IList<TSource>>, IObserver<TSource>
30 {
31 private readonly MinBy<TSource, TKey> _parent;
32 private bool _hasValue;
33 private TKey _lastKey;
34 private List<TSource> _list;
35
36 public _(MinBy<TSource, TKey> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
37 : base(observer, cancel)
38 {
39 _parent = parent;
40
41 _hasValue = false;
42 _lastKey = default(TKey);
43 _list = new List<TSource>();
44 }
45
46 public void OnNext(TSource value)
47 {
48 var key = default(TKey);
49 try
50 {
51 key = _parent._keySelector(value);
52 }
53 catch (Exception ex)
54 {
55 base._observer.OnError(ex);
56 base.Dispose();
57 return;
58 }
59
60 var comparison = 0;
61
62 if (!_hasValue)
63 {
64 _hasValue = true;
65 _lastKey = key;
66 }
67 else
68 {
69 try
70 {
71 comparison = _parent._comparer.Compare(key, _lastKey);
72 }
73 catch (Exception ex)
74 {
75 base._observer.OnError(ex);
76 base.Dispose();
77 return;
78 }
79 }
80
81 if (comparison < 0)
82 {
83 _lastKey = key;
84 _list.Clear();
85 }
86
87 if (comparison <= 0)
88 {
89 _list.Add(value);
90 }
91 }
92
93 public void OnError(Exception error)
94 {
95 base._observer.OnError(error);
96 base.Dispose();
97 }
98
99 public void OnCompleted()
100 {
101 base._observer.OnNext(_list);
102 base._observer.OnCompleted();
103 base.Dispose();
104 }
105 }
106 }
107 }
108 #endif