ToObservable.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. var value = default(T)!;
  33. try
  34. {
  35. hasNext = await e.MoveNextAsync().ConfigureAwait(false);
  36. if (hasNext)
  37. {
  38. value = e.Current;
  39. }
  40. }
  41. catch (Exception ex)
  42. {
  43. if (!ctd.Token.IsCancellationRequested)
  44. {
  45. observer.OnError(ex);
  46. }
  47. return;
  48. }
  49. if (!hasNext)
  50. {
  51. observer.OnCompleted();
  52. return;
  53. }
  54. observer.OnNext(value);
  55. }
  56. while (!ctd.Token.IsCancellationRequested);
  57. }
  58. }
  59. // Fire and forget
  60. Core();
  61. return ctd;
  62. }
  63. }
  64. }
  65. }