AsyncObservable.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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.Threading.Tasks;
  5. namespace System.Reactive.Linq
  6. {
  7. public static partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<T> Create<T>(Func<IAsyncObserver<T>, Task<IAsyncDisposable>> subscribeAsync)
  10. {
  11. if (subscribeAsync == null)
  12. throw new ArgumentNullException(nameof(subscribeAsync));
  13. return new AnonymousAsyncObservable<T>(subscribeAsync);
  14. }
  15. public static Task<IAsyncDisposable> SubscribeAsync<T>(this IAsyncObservable<T> source, Func<T, Task> onNextAsync, Func<Exception, Task> onErrorAsync, Func<Task> onCompletedAsync)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. if (onNextAsync == null)
  20. throw new ArgumentNullException(nameof(onNextAsync));
  21. if (onErrorAsync == null)
  22. throw new ArgumentNullException(nameof(onErrorAsync));
  23. if (onCompletedAsync == null)
  24. throw new ArgumentNullException(nameof(onCompletedAsync));
  25. return source.SubscribeAsync(AsyncObserver.Create(onNextAsync, onErrorAsync, onCompletedAsync));
  26. }
  27. private sealed class AnonymousAsyncObservable<T> : AsyncObservableBase<T>
  28. {
  29. private readonly Func<IAsyncObserver<T>, Task<IAsyncDisposable>> _subscribeAsync;
  30. public AnonymousAsyncObservable(Func<IAsyncObserver<T>, Task<IAsyncDisposable>> subscribeAsync)
  31. {
  32. _subscribeAsync = subscribeAsync;
  33. }
  34. protected override Task<IAsyncDisposable> SubscribeAsyncCore(IAsyncObserver<T> observer) => _subscribeAsync(observer);
  35. }
  36. }
  37. }