AsyncObservable.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 AnonymousAsyncObservable<T>(subscribeAsync);
  15. }
  16. public static Task<IAsyncDisposable> SubscribeAsync<T>(this IAsyncObservable<T> source, Func<T, Task> onNextAsync, Func<Exception, Task> onErrorAsync, Func<Task> onCompletedAsync)
  17. {
  18. if (source == null)
  19. throw new ArgumentNullException(nameof(source));
  20. if (onNextAsync == null)
  21. throw new ArgumentNullException(nameof(onNextAsync));
  22. if (onErrorAsync == null)
  23. throw new ArgumentNullException(nameof(onErrorAsync));
  24. if (onCompletedAsync == null)
  25. throw new ArgumentNullException(nameof(onCompletedAsync));
  26. return source.SubscribeAsync(AsyncObserver.Create(onNextAsync, onErrorAsync, onCompletedAsync));
  27. }
  28. public static Task<IAsyncDisposable> SubscribeSafeAsync<T>(this IAsyncObservable<T> source, IAsyncObserver<T> observer)
  29. {
  30. if (source == null)
  31. throw new ArgumentNullException(nameof(source));
  32. if (observer == null)
  33. throw new ArgumentNullException(nameof(observer));
  34. return CoreAsync();
  35. async Task<IAsyncDisposable> CoreAsync()
  36. {
  37. try
  38. {
  39. return await source.SubscribeAsync(observer);
  40. }
  41. catch (Exception ex)
  42. {
  43. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  44. return AsyncDisposable.Nop;
  45. }
  46. }
  47. }
  48. private sealed class AnonymousAsyncObservable<T> : AsyncObservableBase<T>
  49. {
  50. private readonly Func<IAsyncObserver<T>, Task<IAsyncDisposable>> _subscribeAsync;
  51. public AnonymousAsyncObservable(Func<IAsyncObserver<T>, Task<IAsyncDisposable>> subscribeAsync)
  52. {
  53. _subscribeAsync = subscribeAsync;
  54. }
  55. protected override Task<IAsyncDisposable> SubscribeAsyncCore(IAsyncObserver<T> observer) => _subscribeAsync(observer);
  56. }
  57. }
  58. }