ToObservable.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class AsyncEnumerable
  8. {
  9. public static IObservable<TSource> ToObservable<TSource>(this IAsyncEnumerable<TSource> source)
  10. {
  11. if (source == null)
  12. throw Error.ArgumentNull(nameof(source));
  13. return new ToObservableObservable<TSource>(source);
  14. }
  15. private sealed class ToObservableObservable<T> : IObservable<T>
  16. {
  17. private readonly IAsyncEnumerable<T> _source;
  18. public ToObservableObservable(IAsyncEnumerable<T> source)
  19. {
  20. _source = source;
  21. }
  22. public IDisposable Subscribe(IObserver<T> observer)
  23. {
  24. var ctd = new CancellationTokenDisposable();
  25. async void Core()
  26. {
  27. // REVIEW: fire-and-forget DisposeAsync?
  28. await using (var e = _source.GetAsyncEnumerator(ctd.Token))
  29. {
  30. do
  31. {
  32. bool hasNext;
  33. try
  34. {
  35. hasNext = await e.MoveNextAsync().ConfigureAwait(false);
  36. }
  37. catch (Exception ex)
  38. {
  39. if (!ctd.Token.IsCancellationRequested)
  40. {
  41. observer.OnError(ex);
  42. }
  43. return;
  44. }
  45. if (!hasNext)
  46. {
  47. observer.OnCompleted();
  48. return;
  49. }
  50. observer.OnNext(e.Current);
  51. }
  52. while (!ctd.Token.IsCancellationRequested);
  53. }
  54. }
  55. // Fire and forget
  56. Core();
  57. return ctd;
  58. }
  59. }
  60. }
  61. }