ToLookup.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. namespace System.Reactive.Linq.Observαble
  7. {
  8. class ToLookup<TSource, TKey, TElement> : Producer<ILookup<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 IDisposable Run(IObserver<ILookup<TKey, TElement>> observer, IDisposable cancel, Action<IDisposable> setSink)
  22. {
  23. var sink = new _(this, observer, cancel);
  24. setSink(sink);
  25. return _source.SubscribeSafe(sink);
  26. }
  27. class _ : Sink<ILookup<TKey, TElement>>, IObserver<TSource>
  28. {
  29. private readonly ToLookup<TSource, TKey, TElement> _parent;
  30. private Lookup<TKey, TElement> _lookup;
  31. public _(ToLookup<TSource, TKey, TElement> parent, IObserver<ILookup<TKey, TElement>> observer, IDisposable cancel)
  32. : base(observer, cancel)
  33. {
  34. _parent = parent;
  35. _lookup = new Lookup<TKey, TElement>(_parent._comparer);
  36. }
  37. public void OnNext(TSource value)
  38. {
  39. try
  40. {
  41. _lookup.Add(_parent._keySelector(value), _parent._elementSelector(value));
  42. }
  43. catch (Exception ex)
  44. {
  45. base._observer.OnError(ex);
  46. base.Dispose();
  47. }
  48. }
  49. public void OnError(Exception error)
  50. {
  51. base._observer.OnError(error);
  52. base.Dispose();
  53. }
  54. public void OnCompleted()
  55. {
  56. base._observer.OnNext(_lookup);
  57. base._observer.OnCompleted();
  58. base.Dispose();
  59. }
  60. }
  61. }
  62. }
  63. #endif