AsyncObservable.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 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. private sealed class AnonymousAsyncObservable<T> : IAsyncObservable<T>
  16. {
  17. private readonly Func<IAsyncObserver<T>, Task<IAsyncDisposable>> _subscribeAsync;
  18. public AnonymousAsyncObservable(Func<IAsyncObserver<T>, Task<IAsyncDisposable>> subscribeAsync)
  19. {
  20. _subscribeAsync = subscribeAsync;
  21. }
  22. public async Task<IAsyncDisposable> SubscribeAsync(IAsyncObserver<T> observer)
  23. {
  24. if (observer == null)
  25. throw new ArgumentNullException(nameof(observer));
  26. var autoDetach = new AutoDetachAsyncObserver(observer);
  27. var subscription = await _subscribeAsync(autoDetach).ConfigureAwait(false);
  28. await autoDetach.AssignAsync(subscription);
  29. return autoDetach;
  30. }
  31. private sealed class AutoDetachAsyncObserver : AsyncObserverBase<T>, IAsyncDisposable
  32. {
  33. private readonly IAsyncObserver<T> _observer;
  34. public AutoDetachAsyncObserver(IAsyncObserver<T> observer)
  35. {
  36. _observer = observer;
  37. }
  38. public Task AssignAsync(IAsyncDisposable subscription)
  39. {
  40. throw new NotImplementedException();
  41. }
  42. public Task DisposeAsync()
  43. {
  44. throw new NotImplementedException();
  45. }
  46. protected override Task OnCompletedAsyncCore()
  47. {
  48. throw new NotImplementedException();
  49. }
  50. protected override Task OnErrorAsyncCore(Exception error)
  51. {
  52. throw new NotImplementedException();
  53. }
  54. protected override Task OnNextAsyncCore(T value) => _observer.OnNextAsync(value);
  55. }
  56. }
  57. }
  58. }