1
0

ElementAt.cs 2.2 KB

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