Defer.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. public static IAsyncObservable<TSource> Defer<TSource>(Func<IAsyncObservable<TSource>> observableFactory)
  11. {
  12. if (observableFactory == null)
  13. throw new ArgumentNullException(nameof(observableFactory));
  14. return Defer(() => Task.FromResult(observableFactory()));
  15. }
  16. public static IAsyncObservable<TSource> Defer<TSource>(Func<Task<IAsyncObservable<TSource>>> observableFactory)
  17. {
  18. if (observableFactory == null)
  19. throw new ArgumentNullException(nameof(observableFactory));
  20. return Create<TSource>(async observer =>
  21. {
  22. var source = default(IAsyncObservable<TSource>);
  23. try
  24. {
  25. source = await observableFactory().ConfigureAwait(false);
  26. }
  27. catch (Exception ex)
  28. {
  29. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  30. return AsyncDisposable.Nop;
  31. }
  32. return await source.SubscribeSafeAsync(observer).ConfigureAwait(false);
  33. });
  34. }
  35. }
  36. }