ToDictionary.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. where TKey : notnull
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly Func<TSource, TKey> _keySelector;
  12. private readonly Func<TSource, TElement> _elementSelector;
  13. private readonly IEqualityComparer<TKey> _comparer;
  14. public ToDictionary(IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
  15. {
  16. _source = source;
  17. _keySelector = keySelector;
  18. _elementSelector = elementSelector;
  19. _comparer = comparer;
  20. }
  21. protected override _ CreateSink(IObserver<IDictionary<TKey, TElement>> observer) => new _(this, observer);
  22. protected override void Run(_ sink) => sink.Run(_source);
  23. internal sealed class _ : Sink<TSource, IDictionary<TKey, TElement>>
  24. {
  25. private readonly Func<TSource, TKey> _keySelector;
  26. private readonly Func<TSource, TElement> _elementSelector;
  27. private Dictionary<TKey, TElement> _dictionary;
  28. public _(ToDictionary<TSource, TKey, TElement> parent, IObserver<IDictionary<TKey, TElement>> observer)
  29. : base(observer)
  30. {
  31. _keySelector = parent._keySelector;
  32. _elementSelector = parent._elementSelector;
  33. _dictionary = new Dictionary<TKey, TElement>(parent._comparer);
  34. }
  35. public override void OnNext(TSource value)
  36. {
  37. try
  38. {
  39. _dictionary.Add(_keySelector(value), _elementSelector(value));
  40. }
  41. catch (Exception ex)
  42. {
  43. Cleanup();
  44. ForwardOnError(ex);
  45. }
  46. }
  47. public override void OnError(Exception error)
  48. {
  49. Cleanup();
  50. ForwardOnError(error);
  51. }
  52. public override void OnCompleted()
  53. {
  54. var dictionary = _dictionary;
  55. Cleanup();
  56. ForwardOnNext(dictionary);
  57. ForwardOnCompleted();
  58. }
  59. private void Cleanup()
  60. {
  61. _dictionary = null!;
  62. }
  63. }
  64. }
  65. }