ToDictionary.cs 2.7 KB

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