ToDictionary.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #if !NO_PERF
  5. using System;
  6. using System.Collections.Generic;
  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. public ToDictionary(IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
  16. {
  17. _source = source;
  18. _keySelector = keySelector;
  19. _elementSelector = elementSelector;
  20. _comparer = comparer;
  21. }
  22. protected override IDisposable Run(IObserver<IDictionary<TKey, TElement>> observer, IDisposable cancel, Action<IDisposable> setSink)
  23. {
  24. var sink = new _(this, observer, cancel);
  25. setSink(sink);
  26. return _source.SubscribeSafe(sink);
  27. }
  28. class _ : Sink<IDictionary<TKey, TElement>>, IObserver<TSource>
  29. {
  30. private readonly ToDictionary<TSource, TKey, TElement> _parent;
  31. private Dictionary<TKey, TElement> _dictionary;
  32. public _(ToDictionary<TSource, TKey, TElement> parent, IObserver<IDictionary<TKey, TElement>> observer, IDisposable cancel)
  33. : base(observer, cancel)
  34. {
  35. _parent = parent;
  36. _dictionary = new Dictionary<TKey, TElement>(_parent._comparer);
  37. }
  38. public void OnNext(TSource value)
  39. {
  40. try
  41. {
  42. _dictionary.Add(_parent._keySelector(value), _parent._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. }
  64. #endif