ToDictionary.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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>, ToDictionary<TSource, 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 _ CreateSink(IObserver<IDictionary<TKey, TElement>> observer, IDisposable cancel) => new _(this, observer, cancel);
  21. protected override IDisposable Run(_ sink) => _source.SubscribeSafe(sink);
  22. internal sealed class _ : Sink<IDictionary<TKey, TElement>>, IObserver<TSource>
  23. {
  24. private readonly Func<TSource, TKey> _keySelector;
  25. private readonly Func<TSource, TElement> _elementSelector;
  26. private readonly Dictionary<TKey, TElement> _dictionary;
  27. public _(ToDictionary<TSource, TKey, TElement> parent, IObserver<IDictionary<TKey, TElement>> observer, IDisposable cancel)
  28. : base(observer, cancel)
  29. {
  30. _keySelector = parent._keySelector;
  31. _elementSelector = parent._elementSelector;
  32. _dictionary = new Dictionary<TKey, TElement>(parent._comparer);
  33. }
  34. public void OnNext(TSource value)
  35. {
  36. try
  37. {
  38. _dictionary.Add(_keySelector(value), _elementSelector(value));
  39. }
  40. catch (Exception ex)
  41. {
  42. base._observer.OnError(ex);
  43. base.Dispose();
  44. }
  45. }
  46. public void OnError(Exception error)
  47. {
  48. base._observer.OnError(error);
  49. base.Dispose();
  50. }
  51. public void OnCompleted()
  52. {
  53. base._observer.OnNext(_dictionary);
  54. base._observer.OnCompleted();
  55. base.Dispose();
  56. }
  57. }
  58. }
  59. }