ToObservable.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. await using (var e = _source.GetAsyncEnumerator(ctd.Token))
  28. {
  29. do
  30. {
  31. bool hasNext;
  32. try
  33. {
  34. hasNext = await e.MoveNextAsync().ConfigureAwait(false);
  35. }
  36. catch (Exception ex)
  37. {
  38. if (!ctd.Token.IsCancellationRequested)
  39. {
  40. observer.OnError(ex);
  41. }
  42. return;
  43. }
  44. if (!hasNext)
  45. {
  46. observer.OnCompleted();
  47. return;
  48. }
  49. T v;
  50. try
  51. {
  52. v= e.Current;
  53. }
  54. catch (Exception ex)
  55. {
  56. observer.OnError(ex);
  57. return;
  58. }
  59. observer.OnNext(v);
  60. }
  61. while (!ctd.Token.IsCancellationRequested);
  62. }
  63. }
  64. // Fire and forget
  65. Core();
  66. return ctd;
  67. }
  68. }
  69. }
  70. }