ToLookup.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. using System.Linq;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. internal sealed class ToLookup<TSource, TKey, TElement> : Producer<ILookup<TKey, TElement>, ToLookup<TSource, TKey, TElement>._>
  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 ToLookup(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<ILookup<TKey, TElement>> observer, IDisposable cancel) => new _(this, observer, cancel);
  22. protected override IDisposable Run(_ sink) => _source.SubscribeSafe(sink);
  23. internal sealed class _ : Sink<TSource, ILookup<TKey, TElement>>
  24. {
  25. private readonly Func<TSource, TKey> _keySelector;
  26. private readonly Func<TSource, TElement> _elementSelector;
  27. private readonly Lookup<TKey, TElement> _lookup;
  28. public _(ToLookup<TSource, TKey, TElement> parent, IObserver<ILookup<TKey, TElement>> observer, IDisposable cancel)
  29. : base(observer, cancel)
  30. {
  31. _keySelector = parent._keySelector;
  32. _elementSelector = parent._elementSelector;
  33. _lookup = new Lookup<TKey, TElement>(parent._comparer);
  34. }
  35. public override void OnNext(TSource value)
  36. {
  37. try
  38. {
  39. _lookup.Add(_keySelector(value), _elementSelector(value));
  40. }
  41. catch (Exception ex)
  42. {
  43. ForwardOnError(ex);
  44. }
  45. }
  46. public override void OnCompleted()
  47. {
  48. ForwardOnNext(_lookup);
  49. ForwardOnCompleted();
  50. }
  51. }
  52. }
  53. }