Retry.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.Linq;
  5. using System.Reactive.Disposables;
  6. namespace System.Reactive.Linq
  7. {
  8. partial class AsyncObservable
  9. {
  10. public static IAsyncObservable<TSource> Retry<TSource>(this IAsyncObservable<TSource> source)
  11. {
  12. if (source == null)
  13. throw new ArgumentNullException(nameof(source));
  14. return Create<TSource>(async observer =>
  15. {
  16. var (sink, inner) = AsyncObserver.Retry(observer, source);
  17. var subscription = await source.SubscribeSafeAsync(sink).ConfigureAwait(false);
  18. return StableCompositeAsyncDisposable.Create(subscription, inner);
  19. });
  20. }
  21. public static IAsyncObservable<TSource> Retry<TSource>(this IAsyncObservable<TSource> source, int retryCount)
  22. {
  23. if (source == null)
  24. throw new ArgumentNullException(nameof(source));
  25. if (retryCount < 0)
  26. throw new ArgumentOutOfRangeException(nameof(retryCount));
  27. return Create<TSource>(async observer =>
  28. {
  29. var (sink, inner) = AsyncObserver.Retry(observer, source, retryCount);
  30. var subscription = await source.SubscribeSafeAsync(sink).ConfigureAwait(false);
  31. return StableCompositeAsyncDisposable.Create(subscription, inner);
  32. });
  33. }
  34. }
  35. partial class AsyncObserver
  36. {
  37. public static (IAsyncObserver<TSource>, IAsyncDisposable) Retry<TSource>(IAsyncObserver<TSource> observer, IAsyncObservable<TSource> source)
  38. {
  39. if (observer == null)
  40. throw new ArgumentNullException(nameof(observer));
  41. if (source == null)
  42. throw new ArgumentNullException(nameof(source));
  43. return Catch(observer, Repeat(source).GetEnumerator());
  44. }
  45. public static (IAsyncObserver<TSource>, IAsyncDisposable) Retry<TSource>(IAsyncObserver<TSource> observer, IAsyncObservable<TSource> source, int retryCount)
  46. {
  47. if (observer == null)
  48. throw new ArgumentNullException(nameof(observer));
  49. if (source == null)
  50. throw new ArgumentNullException(nameof(source));
  51. if (retryCount < 0)
  52. throw new ArgumentOutOfRangeException(nameof(retryCount));
  53. return Catch(observer, Enumerable.Repeat(source, retryCount).GetEnumerator());
  54. }
  55. }
  56. }