Defer.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. using System.Reactive.Disposables;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Reactive.Linq
  8. {
  9. public partial class AsyncObservable
  10. {
  11. public static IAsyncObservable<TSource> Defer<TSource>(Func<IAsyncObservable<TSource>> observableFactory)
  12. {
  13. if (observableFactory == null)
  14. throw new ArgumentNullException(nameof(observableFactory));
  15. return Defer(() => new ValueTask<IAsyncObservable<TSource>>(observableFactory()));
  16. }
  17. public static IAsyncObservable<TSource> DeferAsync<TSource>(Func<ValueTask<IAsyncObservable<TSource>>> observableFactory) => Defer(observableFactory);
  18. public static IAsyncObservable<TSource> Defer<TSource>(Func<ValueTask<IAsyncObservable<TSource>>> observableFactory)
  19. {
  20. if (observableFactory == null)
  21. throw new ArgumentNullException(nameof(observableFactory));
  22. return Create<TSource>(async observer =>
  23. {
  24. var source = default(IAsyncObservable<TSource>);
  25. try
  26. {
  27. source = await observableFactory().ConfigureAwait(false);
  28. }
  29. catch (Exception ex)
  30. {
  31. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  32. return AsyncDisposable.Nop;
  33. }
  34. return await source.SubscribeSafeAsync(observer).ConfigureAwait(false);
  35. });
  36. }
  37. public static IAsyncObservable<TSource> DeferAsync<TSource>(Func<CancellationToken, ValueTask<IAsyncObservable<TSource>>> observableFactory) => Defer(observableFactory);
  38. public static IAsyncObservable<TSource> Defer<TSource>(Func<CancellationToken, ValueTask<IAsyncObservable<TSource>>> observableFactory)
  39. {
  40. if (observableFactory == null)
  41. throw new ArgumentNullException(nameof(observableFactory));
  42. return StartAsync(observableFactory).Merge();
  43. }
  44. }
  45. }