ToObservable.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 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. if (tcs != null)
  102. {
  103. tcs.TrySetResult(false);
  104. }
  105. }
  106. public void OnError(Exception error)
  107. {
  108. var tcs = default(TaskCompletionSource<bool>);
  109. lock (SyncRoot)
  110. {
  111. Error = error;
  112. if (TaskCompletionSource != null)
  113. {
  114. tcs = TaskCompletionSource;
  115. TaskCompletionSource = null;
  116. }
  117. }
  118. if (tcs != null)
  119. {
  120. tcs.TrySetException(error);
  121. }
  122. }
  123. public void OnNext(T value)
  124. {
  125. var tcs = default(TaskCompletionSource<bool>);
  126. lock (SyncRoot)
  127. {
  128. if (TaskCompletionSource == null)
  129. {
  130. Values.Enqueue(value);
  131. }
  132. else
  133. {
  134. Current = value;
  135. tcs = TaskCompletionSource;
  136. TaskCompletionSource = null;
  137. }
  138. }
  139. if (tcs != null)
  140. {
  141. tcs.TrySetResult(true);
  142. }
  143. }
  144. }
  145. private class ToObservableObservable<T> : IObservable<T>
  146. {
  147. private readonly IAsyncEnumerable<T> source;
  148. public ToObservableObservable(IAsyncEnumerable<T> source)
  149. {
  150. this.source = source;
  151. }
  152. public IDisposable Subscribe(IObserver<T> observer)
  153. {
  154. var ctd = new CancellationTokenDisposable();
  155. var e = source.GetAsyncEnumerator();
  156. var f = default(Action);
  157. f = () => e.MoveNextAsync()
  158. .ContinueWith(async t =>
  159. {
  160. if (t.IsFaulted)
  161. {
  162. observer.OnError(t.Exception);
  163. await e.DisposeAsync().ConfigureAwait(false);
  164. }
  165. else if (t.IsCanceled)
  166. {
  167. await e.DisposeAsync().ConfigureAwait(false);
  168. }
  169. else if (t.IsCompleted)
  170. {
  171. if (t.Result)
  172. {
  173. observer.OnNext(e.Current);
  174. if (!ctd.Token.IsCancellationRequested)
  175. f();
  176. //In case cancellation is requested, this could only have happened
  177. //by disposing the returned composite disposable (see below).
  178. //In that case, e will be disposed too, so there is no need to dispose e here.
  179. }
  180. else
  181. {
  182. observer.OnCompleted();
  183. await e.DisposeAsync().ConfigureAwait(false);
  184. }
  185. }
  186. }, ctd.Token);
  187. f();
  188. return Disposable.Create(ctd, Disposable.Create(() => { e.DisposeAsync(); /* REVIEW: fire-and-forget? */ }));
  189. }
  190. }
  191. }
  192. }