ToObservable.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. using System.Threading.Tasks;
  6. namespace System.Linq
  7. {
  8. public static partial class AsyncEnumerable
  9. {
  10. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IObservable<TSource> source)
  11. {
  12. if (source == null)
  13. throw new ArgumentNullException(nameof(source));
  14. return CreateEnumerable(
  15. () =>
  16. {
  17. var observer = new ToAsyncEnumerableObserver<TSource>();
  18. var subscription = source.Subscribe(observer);
  19. return CreateEnumerator(
  20. tcs =>
  21. {
  22. var hasValue = false;
  23. var hasCompleted = false;
  24. var error = default(Exception);
  25. lock (observer.SyncRoot)
  26. {
  27. if (observer.Values.Count > 0)
  28. {
  29. hasValue = true;
  30. observer.Current = observer.Values.Dequeue();
  31. }
  32. else if (observer.HasCompleted)
  33. {
  34. hasCompleted = true;
  35. }
  36. else if (observer.Error != null)
  37. {
  38. error = observer.Error;
  39. }
  40. else
  41. {
  42. observer.TaskCompletionSource = tcs;
  43. }
  44. }
  45. if (hasValue)
  46. {
  47. tcs.TrySetResult(true);
  48. }
  49. else if (hasCompleted)
  50. {
  51. tcs.TrySetResult(false);
  52. }
  53. else if (error != null)
  54. {
  55. tcs.TrySetException(error);
  56. }
  57. return tcs.Task;
  58. },
  59. () => observer.Current,
  60. () =>
  61. {
  62. subscription.Dispose();
  63. // Should we cancel in-flight operations somehow?
  64. return TaskExt.True;
  65. });
  66. });
  67. }
  68. public static IObservable<TSource> ToObservable<TSource>(this IAsyncEnumerable<TSource> source)
  69. {
  70. if (source == null)
  71. throw new ArgumentNullException(nameof(source));
  72. return new ToObservableObservable<TSource>(source);
  73. }
  74. private sealed class ToAsyncEnumerableObserver<T> : IObserver<T>
  75. {
  76. public readonly Queue<T> Values;
  77. public T Current;
  78. public Exception Error;
  79. public bool HasCompleted;
  80. public TaskCompletionSource<bool> TaskCompletionSource;
  81. public ToAsyncEnumerableObserver()
  82. {
  83. Values = new Queue<T>();
  84. }
  85. public object SyncRoot
  86. {
  87. get { return Values; }
  88. }
  89. public void OnCompleted()
  90. {
  91. var tcs = default(TaskCompletionSource<bool>);
  92. lock (SyncRoot)
  93. {
  94. HasCompleted = true;
  95. if (TaskCompletionSource != null)
  96. {
  97. tcs = TaskCompletionSource;
  98. TaskCompletionSource = null;
  99. }
  100. }
  101. tcs?.TrySetResult(false);
  102. }
  103. public void OnError(Exception error)
  104. {
  105. var tcs = default(TaskCompletionSource<bool>);
  106. lock (SyncRoot)
  107. {
  108. Error = error;
  109. if (TaskCompletionSource != null)
  110. {
  111. tcs = TaskCompletionSource;
  112. TaskCompletionSource = null;
  113. }
  114. }
  115. tcs?.TrySetException(error);
  116. }
  117. public void OnNext(T value)
  118. {
  119. var tcs = default(TaskCompletionSource<bool>);
  120. lock (SyncRoot)
  121. {
  122. if (TaskCompletionSource == null)
  123. {
  124. Values.Enqueue(value);
  125. }
  126. else
  127. {
  128. Current = value;
  129. tcs = TaskCompletionSource;
  130. TaskCompletionSource = null;
  131. }
  132. }
  133. tcs?.TrySetResult(true);
  134. }
  135. }
  136. private sealed class ToObservableObservable<T> : IObservable<T>
  137. {
  138. private readonly IAsyncEnumerable<T> source;
  139. public ToObservableObservable(IAsyncEnumerable<T> source)
  140. {
  141. this.source = source;
  142. }
  143. public IDisposable Subscribe(IObserver<T> observer)
  144. {
  145. var ctd = new CancellationTokenDisposable();
  146. var e = source.GetAsyncEnumerator();
  147. var f = default(Action);
  148. f = () => e.MoveNextAsync()
  149. .ContinueWith(async t =>
  150. {
  151. if (t.IsFaulted)
  152. {
  153. observer.OnError(t.Exception);
  154. await e.DisposeAsync().ConfigureAwait(false);
  155. }
  156. else if (t.IsCanceled)
  157. {
  158. await e.DisposeAsync().ConfigureAwait(false);
  159. }
  160. else if (t.IsCompleted)
  161. {
  162. if (t.Result)
  163. {
  164. observer.OnNext(e.Current);
  165. if (!ctd.Token.IsCancellationRequested)
  166. f();
  167. //In case cancellation is requested, this could only have happened
  168. //by disposing the returned composite disposable (see below).
  169. //In that case, e will be disposed too, so there is no need to dispose e here.
  170. }
  171. else
  172. {
  173. observer.OnCompleted();
  174. await e.DisposeAsync().ConfigureAwait(false);
  175. }
  176. }
  177. }, ctd.Token);
  178. f();
  179. return Disposable.Create(ctd, Disposable.Create(() => { e.DisposeAsync(); /* REVIEW: fire-and-forget? */ }));
  180. }
  181. }
  182. }
  183. }