ToLookup.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. using System.Linq;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. class ToLookup<TSource, TKey, TElement> : Producer<ILookup<TKey, TElement>>
  11. {
  12. private readonly IObservable<TSource> _source;
  13. private readonly Func<TSource, TKey> _keySelector;
  14. private readonly Func<TSource, TElement> _elementSelector;
  15. private readonly IEqualityComparer<TKey> _comparer;
  16. public ToLookup(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. protected override IDisposable Run(IObserver<ILookup<TKey, TElement>> observer, IDisposable cancel, Action<IDisposable> setSink)
  24. {
  25. var sink = new _(this, observer, cancel);
  26. setSink(sink);
  27. return _source.SubscribeSafe(sink);
  28. }
  29. class _ : Sink<ILookup<TKey, TElement>>, IObserver<TSource>
  30. {
  31. private readonly ToLookup<TSource, TKey, TElement> _parent;
  32. private Lookup<TKey, TElement> _lookup;
  33. public _(ToLookup<TSource, TKey, TElement> parent, IObserver<ILookup<TKey, TElement>> observer, IDisposable cancel)
  34. : base(observer, cancel)
  35. {
  36. _parent = parent;
  37. _lookup = new Lookup<TKey, TElement>(_parent._comparer);
  38. }
  39. public void OnNext(TSource value)
  40. {
  41. try
  42. {
  43. _lookup.Add(_parent._keySelector(value), _parent._elementSelector(value));
  44. }
  45. catch (Exception ex)
  46. {
  47. base._observer.OnError(ex);
  48. base.Dispose();
  49. }
  50. }
  51. public void OnError(Exception error)
  52. {
  53. base._observer.OnError(error);
  54. base.Dispose();
  55. }
  56. public void OnCompleted()
  57. {
  58. base._observer.OnNext(_lookup);
  59. base._observer.OnCompleted();
  60. base.Dispose();
  61. }
  62. }
  63. }
  64. }
  65. #endif