Debian Codegraph @

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