ElementAtOrDefault.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. 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<TSource>(observer => source.SubscribeSafeAsync(AsyncObserver.ElementAtOrDefault(observer, index)));
  15. }
  16. }
  17. partial class AsyncObserver
  18. {
  19. public static IAsyncObserver<TSource> ElementAtOrDefault<TSource>(IAsyncObserver<TSource> observer, int index)
  20. {
  21. if (observer == null)
  22. throw new ArgumentNullException(nameof(observer));
  23. if (index < 0)
  24. throw new ArgumentOutOfRangeException(nameof(index));
  25. return Create<TSource>(
  26. async x =>
  27. {
  28. if (index-- == 0)
  29. {
  30. await observer.OnNextAsync(x).ConfigureAwait(false);
  31. await observer.OnCompletedAsync().ConfigureAwait(false);
  32. }
  33. },
  34. observer.OnErrorAsync,
  35. async () =>
  36. {
  37. await observer.OnNextAsync(default(TSource)).ConfigureAwait(false);
  38. await observer.OnCompletedAsync().ConfigureAwait(false);
  39. }
  40. );
  41. }
  42. }
  43. }