ElementAt.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. using System.Threading.Tasks;
  5. namespace System.Reactive.Linq
  6. {
  7. 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<TSource>(observer => source.SubscribeSafeAsync(AsyncObserver.ElementAt(observer, index)));
  16. }
  17. }
  18. partial class AsyncObserver
  19. {
  20. public static IAsyncObserver<TSource> ElementAt<TSource>(IAsyncObserver<TSource> observer, int index)
  21. {
  22. if (observer == null)
  23. throw new ArgumentNullException(nameof(observer));
  24. if (index < 0)
  25. throw new ArgumentOutOfRangeException(nameof(index));
  26. return Create<TSource>(
  27. async x =>
  28. {
  29. if (index-- == 0)
  30. {
  31. await observer.OnNextAsync(x).ConfigureAwait(false);
  32. await observer.OnCompletedAsync().ConfigureAwait(false);
  33. }
  34. },
  35. observer.OnErrorAsync,
  36. async () =>
  37. {
  38. await observer.OnErrorAsync(new ArgumentOutOfRangeException("The element at the specified index was not found.")).ConfigureAwait(false);
  39. }
  40. );
  41. }
  42. }
  43. }