| 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 Distinct<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 Distinct(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 Distinct<TSource, TKey> _parent; |
| 32 |
private HashSet<TKey> _hashSet; |
| 33 |
|
| 34 |
public _(Distinct<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel) |
| 35 |
: base(observer, cancel) |
| 36 |
{ |
| 37 |
_parent = parent; |
| 38 |
_hashSet = new HashSet<TKey>(_parent._comparer); |
| 39 |
} |
| 40 |
|
| 41 |
public void OnNext(TSource value) |
| 42 |
{ |
| 43 |
var key = default(TKey); |
| 44 |
var hasAdded = false; |
| 45 |
try |
| 46 |
{ |
| 47 |
key = _parent._keySelector(value); |
| 48 |
hasAdded = _hashSet.Add(key); |
| 49 |
} |
| 50 |
catch (Exception exception) |
| 51 |
{ |
| 52 |
base._observer.OnError(exception); |
| 53 |
base.Dispose(); |
| 54 |
return; |
| 55 |
} |
| 56 |
|
| 57 |
if (hasAdded) |
| 58 |
base._observer.OnNext(value); |
| 59 |
} |
| 60 |
|
| 61 |
public void OnError(Exception error) |
| 62 |
{ |
| 63 |
base._observer.OnError(error); |
| 64 |
base.Dispose(); |
| 65 |
} |
| 66 |
|
| 67 |
public void OnCompleted() |
| 68 |
{ |
| 69 |
base._observer.OnCompleted(); |
| 70 |
base.Dispose(); |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
#endif |