ElementAt.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. internal sealed class ElementAt<TSource> : Producer<TSource, ElementAt<TSource>._>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. private readonly int _index;
  10. public ElementAt(IObservable<TSource> source, int index)
  11. {
  12. _source = source;
  13. _index = index;
  14. }
  15. protected override _ CreateSink(IObserver<TSource> observer) => new _(_index, observer);
  16. protected override void Run(_ sink) => sink.Run(_source);
  17. internal sealed class _ : IdentitySink<TSource>
  18. {
  19. private int _i;
  20. public _(int index, IObserver<TSource> observer)
  21. : base(observer)
  22. {
  23. _i = index;
  24. }
  25. public override void OnNext(TSource value)
  26. {
  27. if (_i == 0)
  28. {
  29. ForwardOnNext(value);
  30. ForwardOnCompleted();
  31. }
  32. _i--;
  33. }
  34. public override void OnCompleted()
  35. {
  36. if (_i >= 0)
  37. {
  38. ForwardOnError(new ArgumentOutOfRangeException("index"));
  39. }
  40. }
  41. }
  42. }
  43. }