ElementAt.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Threading.Tasks;
  5. namespace System.Reactive.Linq
  6. {
  7. public partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<TSource> ElementAt<TSource>(this IAsyncObservable<TSource> source, int index)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. if (index < 0)
  14. throw new ArgumentOutOfRangeException(nameof(index));
  15. return Create(
  16. source,
  17. index,
  18. static (source, index, observer) => source.SubscribeSafeAsync(AsyncObserver.ElementAt(observer, index)));
  19. }
  20. }
  21. public partial class AsyncObserver
  22. {
  23. public static IAsyncObserver<TSource> ElementAt<TSource>(IAsyncObserver<TSource> observer, int index)
  24. {
  25. if (observer == null)
  26. throw new ArgumentNullException(nameof(observer));
  27. if (index < 0)
  28. throw new ArgumentOutOfRangeException(nameof(index));
  29. return Create<TSource>(
  30. async x =>
  31. {
  32. if (index-- == 0)
  33. {
  34. await observer.OnNextAsync(x).ConfigureAwait(false);
  35. await observer.OnCompletedAsync().ConfigureAwait(false);
  36. }
  37. },
  38. observer.OnErrorAsync,
  39. async () =>
  40. {
  41. await observer.OnErrorAsync(new ArgumentOutOfRangeException("The element at the specified index was not found.")).ConfigureAwait(false);
  42. }
  43. );
  44. }
  45. }
  46. }