AsyncObservable.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. public static partial class AsyncObservable
  9. {
  10. public static IAsyncObservable<T> Create<T>(Func<IAsyncObserver<T>, Task<IAsyncDisposable>> subscribeAsync)
  11. {
  12. if (subscribeAsync == null)
  13. throw new ArgumentNullException(nameof(subscribeAsync));
  14. return new AsyncObservable<T>(subscribeAsync);
  15. }
  16. public static Task<IAsyncDisposable> SubscribeSafeAsync<T>(this IAsyncObservable<T> source, IAsyncObserver<T> observer)
  17. {
  18. if (source == null)
  19. throw new ArgumentNullException(nameof(source));
  20. if (observer == null)
  21. throw new ArgumentNullException(nameof(observer));
  22. return CoreAsync();
  23. async Task<IAsyncDisposable> CoreAsync()
  24. {
  25. try
  26. {
  27. return await source.SubscribeAsync(observer);
  28. }
  29. catch (Exception ex)
  30. {
  31. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  32. return AsyncDisposable.Nop;
  33. }
  34. }
  35. }
  36. }
  37. }