While.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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.Reactive.Disposables;
  5. using System.Threading.Tasks;
  6. namespace System.Reactive.Linq
  7. {
  8. partial class AsyncObservable
  9. {
  10. // REVIEW: Use a tail-recursive sink.
  11. public static IAsyncObservable<TSource> While<TSource>(Func<bool> condition, IAsyncObservable<TSource> source)
  12. {
  13. if (condition == null)
  14. throw new ArgumentNullException(nameof(condition));
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. return Create<TSource>(async observer =>
  18. {
  19. var subscription = new SerialAsyncDisposable();
  20. var o = default(IAsyncObserver<TSource>);
  21. o = AsyncObserver.CreateUnsafe<TSource>(
  22. observer.OnNextAsync,
  23. observer.OnErrorAsync,
  24. MoveNext
  25. );
  26. async Task MoveNext()
  27. {
  28. var b = default(bool);
  29. try
  30. {
  31. b = condition();
  32. }
  33. catch (Exception ex)
  34. {
  35. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  36. }
  37. if (b)
  38. {
  39. var sad = new SingleAssignmentAsyncDisposable();
  40. await subscription.AssignAsync(sad).ConfigureAwait(false);
  41. var d = await source.SubscribeSafeAsync(o).ConfigureAwait(false);
  42. await sad.AssignAsync(d).ConfigureAwait(false);
  43. }
  44. else
  45. {
  46. await observer.OnCompletedAsync().ConfigureAwait(false);
  47. }
  48. }
  49. await MoveNext().ConfigureAwait(false);
  50. return subscription;
  51. });
  52. }
  53. }
  54. }