Take.cs 1.6 KB

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