ToObservable.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. /// <summary>
  10. /// Converts an async-enumerable sequence to an observable sequence.
  11. /// </summary>
  12. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  13. /// <param name="source">Enumerable sequence to convert to an observable sequence.</param>
  14. /// <returns>The observable sequence whose elements are pulled from the given enumerable sequence.</returns>
  15. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  16. public static IObservable<TSource> ToObservable<TSource>(this IAsyncEnumerable<TSource> source)
  17. {
  18. if (source == null)
  19. throw Error.ArgumentNull(nameof(source));
  20. return new ToObservableObservable<TSource>(source);
  21. }
  22. private sealed class ToObservableObservable<T> : IObservable<T>
  23. {
  24. private readonly IAsyncEnumerable<T> _source;
  25. public ToObservableObservable(IAsyncEnumerable<T> source)
  26. {
  27. _source = source;
  28. }
  29. public IDisposable Subscribe(IObserver<T> observer)
  30. {
  31. var ctd = new CancellationTokenDisposable();
  32. async void Core()
  33. {
  34. await using (var e = _source.GetAsyncEnumerator(ctd.Token))
  35. {
  36. do
  37. {
  38. bool hasNext;
  39. var value = default(T)!;
  40. try
  41. {
  42. hasNext = await e.MoveNextAsync().ConfigureAwait(false);
  43. if (hasNext)
  44. {
  45. value = e.Current;
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. if (!ctd.Token.IsCancellationRequested)
  51. {
  52. observer.OnError(ex);
  53. }
  54. return;
  55. }
  56. if (!hasNext)
  57. {
  58. observer.OnCompleted();
  59. return;
  60. }
  61. observer.OnNext(value);
  62. }
  63. while (!ctd.Token.IsCancellationRequested);
  64. }
  65. }
  66. // Fire and forget
  67. Core();
  68. return ctd;
  69. }
  70. }
  71. }
  72. }