ToObservable.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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 AsyncEnumerableEx
  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. do
  36. {
  37. bool hasNext;
  38. var value = default(T)!;
  39. try
  40. {
  41. hasNext = await e.MoveNextAsync().ConfigureAwait(false);
  42. if (hasNext)
  43. {
  44. value = e.Current;
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. if (!ctd.Token.IsCancellationRequested)
  50. {
  51. observer.OnError(ex);
  52. }
  53. return;
  54. }
  55. if (!hasNext)
  56. {
  57. observer.OnCompleted();
  58. return;
  59. }
  60. observer.OnNext(value);
  61. }
  62. while (!ctd.Token.IsCancellationRequested);
  63. }
  64. // Fire and forget
  65. Core();
  66. return ctd;
  67. }
  68. }
  69. }
  70. }