Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/ToDictionary.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 ToDictionary<TSource, TKey, TElement> : Producer<IDictionary<TKey, TElement>>
10 {
11 private readonly IObservable<TSource> _source;
12 private readonly Func<TSource, TKey> _keySelector;
13 private readonly Func<TSource, TElement> _elementSelector;
14 private readonly IEqualityComparer<TKey> _comparer;
15
16 public ToDictionary(IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
17 {
18 _source = source;
19 _keySelector = keySelector;
20 _elementSelector = elementSelector;
21 _comparer = comparer;
22 }
23
24 protected override IDisposable Run(IObserver<IDictionary<TKey, TElement>> observer, IDisposable cancel, Action<IDisposable> setSink)
25 {
26 var sink = new _(this, observer, cancel);
27 setSink(sink);
28 return _source.SubscribeSafe(sink);
29 }
30
31 class _ : Sink<IDictionary<TKey, TElement>>, IObserver<TSource>
32 {
33 private readonly ToDictionary<TSource, TKey, TElement> _parent;
34 private Dictionary<TKey, TElement> _dictionary;
35
36 public _(ToDictionary<TSource, TKey, TElement> parent, IObserver<IDictionary<TKey, TElement>> observer, IDisposable cancel)
37 : base(observer, cancel)
38 {
39 _parent = parent;
40 _dictionary = new Dictionary<TKey, TElement>(_parent._comparer);
41 }
42
43 public void OnNext(TSource value)
44 {
45 try
46 {
47 _dictionary.Add(_parent._keySelector(value), _parent._elementSelector(value));
48 }
49 catch (Exception ex)
50 {
51 base._observer.OnError(ex);
52 base.Dispose();
53 }
54 }
55
56 public void OnError(Exception error)
57 {
58 base._observer.OnError(error);
59 base.Dispose();
60 }
61
62 public void OnCompleted()
63 {
64 base._observer.OnNext(_dictionary);
65 base._observer.OnCompleted();
66 base.Dispose();
67 }
68 }
69 }
70 }
71 #endif