1
0

ElementAt.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. class ElementAt<TSource> : Producer<TSource>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. private readonly int _index;
  10. private readonly bool _throwOnEmpty;
  11. public ElementAt(IObservable<TSource> source, int index, bool throwOnEmpty)
  12. {
  13. _source = source;
  14. _index = index;
  15. _throwOnEmpty = throwOnEmpty;
  16. }
  17. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  18. {
  19. var sink = new _(this, observer, cancel);
  20. setSink(sink);
  21. return _source.SubscribeSafe(sink);
  22. }
  23. class _ : Sink<TSource>, IObserver<TSource>
  24. {
  25. private readonly ElementAt<TSource> _parent;
  26. private int _i;
  27. public _(ElementAt<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  28. : base(observer, cancel)
  29. {
  30. _parent = parent;
  31. _i = _parent._index;
  32. }
  33. public void OnNext(TSource value)
  34. {
  35. if (_i == 0)
  36. {
  37. base._observer.OnNext(value);
  38. base._observer.OnCompleted();
  39. base.Dispose();
  40. }
  41. _i--;
  42. }
  43. public void OnError(Exception error)
  44. {
  45. base._observer.OnError(error);
  46. base.Dispose();
  47. }
  48. public void OnCompleted()
  49. {
  50. if (_parent._throwOnEmpty)
  51. {
  52. base._observer.OnError(new ArgumentOutOfRangeException("index"));
  53. }
  54. else
  55. {
  56. base._observer.OnNext(default(TSource));
  57. base._observer.OnCompleted();
  58. }
  59. base.Dispose();
  60. }
  61. }
  62. }
  63. }
  64. #endif