ToObservable.cs 8.2 KB

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