ElementAtOrDefault.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. namespace System.Reactive.Linq
  5. {
  6. public partial class AsyncObservable
  7. {
  8. public static IAsyncObservable<TSource> ElementAtOrDefault<TSource>(this IAsyncObservable<TSource> source, int index)
  9. {
  10. if (source == null)
  11. throw new ArgumentNullException(nameof(source));
  12. if (index < 0)
  13. throw new ArgumentOutOfRangeException(nameof(index));
  14. return Create(
  15. source,
  16. index,
  17. static (source, index, observer) => source.SubscribeSafeAsync(AsyncObserver.ElementAtOrDefault(observer, index)));
  18. }
  19. }
  20. public partial class AsyncObserver
  21. {
  22. public static IAsyncObserver<TSource> ElementAtOrDefault<TSource>(IAsyncObserver<TSource> observer, int index)
  23. {
  24. if (observer == null)
  25. throw new ArgumentNullException(nameof(observer));
  26. if (index < 0)
  27. throw new ArgumentOutOfRangeException(nameof(index));
  28. return Create<TSource>(
  29. async x =>
  30. {
  31. if (index-- == 0)
  32. {
  33. await observer.OnNextAsync(x).ConfigureAwait(false);
  34. await observer.OnCompletedAsync().ConfigureAwait(false);
  35. }
  36. },
  37. observer.OnErrorAsync,
  38. async () =>
  39. {
  40. await observer.OnNextAsync(default).ConfigureAwait(false);
  41. await observer.OnCompletedAsync().ConfigureAwait(false);
  42. }
  43. );
  44. }
  45. }
  46. }