Amb.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. using System.Linq;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Reactive.Linq
  10. {
  11. public partial class AsyncObservable
  12. {
  13. public static IAsyncObservable<TSource> Amb<TSource>(this IAsyncObservable<TSource> first, IAsyncObservable<TSource> second)
  14. {
  15. if (first == null)
  16. throw new ArgumentNullException(nameof(first));
  17. if (second == null)
  18. throw new ArgumentNullException(nameof(second));
  19. return Create(
  20. first,
  21. second,
  22. default(TSource),
  23. async (first, second, observer) =>
  24. {
  25. var firstSubscription = new SingleAssignmentAsyncDisposable();
  26. var secondSubscription = new SingleAssignmentAsyncDisposable();
  27. var (firstObserver, secondObserver) = AsyncObserver.Amb(observer, firstSubscription, secondSubscription);
  28. var firstTask = first.SubscribeSafeAsync(firstObserver).AsTask().ContinueWith(d => firstSubscription.AssignAsync(d.Result).AsTask()).Unwrap();
  29. var secondTask = second.SubscribeSafeAsync(secondObserver).AsTask().ContinueWith(d => secondSubscription.AssignAsync(d.Result).AsTask()).Unwrap();
  30. await Task.WhenAll(firstTask, secondTask).ConfigureAwait(false);
  31. return StableCompositeAsyncDisposable.Create(firstSubscription, secondSubscription);
  32. });
  33. }
  34. public static IAsyncObservable<TSource> Amb<TSource>(this IEnumerable<IAsyncObservable<TSource>> sources) => Amb(sources.ToArray());
  35. public static IAsyncObservable<TSource> Amb<TSource>(params IAsyncObservable<TSource>[] sources)
  36. {
  37. if (sources == null)
  38. throw new ArgumentNullException(nameof(sources));
  39. return Create<TSource>(async observer =>
  40. {
  41. var count = sources.Length;
  42. var subscriptions = new SingleAssignmentAsyncDisposable[count];
  43. for (var i = 0; i < count; i++)
  44. {
  45. subscriptions[i] = new SingleAssignmentAsyncDisposable();
  46. }
  47. var observers = AsyncObserver.Amb(observer, subscriptions);
  48. var tasks = new Task[count];
  49. for (var i = 0; i < count; i++)
  50. {
  51. tasks[i] = sources[i].SubscribeSafeAsync(observers[i]).AsTask().ContinueWith(d => subscriptions[i].AssignAsync(d.Result).AsTask()).Unwrap();
  52. }
  53. await Task.WhenAll(tasks).ConfigureAwait(false);
  54. return StableCompositeAsyncDisposable.Create(subscriptions);
  55. });
  56. }
  57. }
  58. public partial class AsyncObserver
  59. {
  60. public static (IAsyncObserver<TSource>, IAsyncObserver<TSource>) Amb<TSource>(IAsyncObserver<TSource> observer, IAsyncDisposable first, IAsyncDisposable second)
  61. {
  62. if (observer == null)
  63. throw new ArgumentNullException(nameof(observer));
  64. if (first == null)
  65. throw new ArgumentNullException(nameof(first));
  66. if (second == null)
  67. throw new ArgumentNullException(nameof(second));
  68. var gate = new AsyncLock();
  69. var state = AmbState.None;
  70. return
  71. (
  72. Create<TSource>(
  73. async x =>
  74. {
  75. using (await gate.LockAsync().ConfigureAwait(false))
  76. {
  77. if (state == AmbState.None)
  78. {
  79. state = AmbState.First;
  80. await second.DisposeAsync().ConfigureAwait(false);
  81. }
  82. if (state == AmbState.First)
  83. {
  84. await observer.OnNextAsync(x).ConfigureAwait(false);
  85. }
  86. }
  87. },
  88. async ex =>
  89. {
  90. using (await gate.LockAsync().ConfigureAwait(false))
  91. {
  92. if (state == AmbState.None)
  93. {
  94. state = AmbState.First;
  95. await second.DisposeAsync().ConfigureAwait(false);
  96. }
  97. if (state == AmbState.First)
  98. {
  99. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  100. }
  101. }
  102. },
  103. async () =>
  104. {
  105. using (await gate.LockAsync().ConfigureAwait(false))
  106. {
  107. if (state == AmbState.None)
  108. {
  109. state = AmbState.First;
  110. await second.DisposeAsync().ConfigureAwait(false);
  111. }
  112. if (state == AmbState.First)
  113. {
  114. await observer.OnCompletedAsync().ConfigureAwait(false);
  115. }
  116. }
  117. }
  118. ),
  119. Create<TSource>(
  120. async x =>
  121. {
  122. using (await gate.LockAsync().ConfigureAwait(false))
  123. {
  124. if (state == AmbState.None)
  125. {
  126. state = AmbState.Second;
  127. await first.DisposeAsync().ConfigureAwait(false);
  128. }
  129. if (state == AmbState.Second)
  130. {
  131. await observer.OnNextAsync(x).ConfigureAwait(false);
  132. }
  133. }
  134. },
  135. async ex =>
  136. {
  137. using (await gate.LockAsync().ConfigureAwait(false))
  138. {
  139. if (state == AmbState.None)
  140. {
  141. state = AmbState.Second;
  142. await first.DisposeAsync().ConfigureAwait(false);
  143. }
  144. if (state == AmbState.Second)
  145. {
  146. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  147. }
  148. }
  149. },
  150. async () =>
  151. {
  152. using (await gate.LockAsync().ConfigureAwait(false))
  153. {
  154. if (state == AmbState.None)
  155. {
  156. state = AmbState.Second;
  157. await first.DisposeAsync().ConfigureAwait(false);
  158. }
  159. if (state == AmbState.Second)
  160. {
  161. await observer.OnCompletedAsync().ConfigureAwait(false);
  162. }
  163. }
  164. }
  165. )
  166. );
  167. }
  168. public static IAsyncObserver<TSource>[] Amb<TSource>(IAsyncObserver<TSource> observer, IAsyncDisposable[] subscriptions)
  169. {
  170. if (observer == null)
  171. throw new ArgumentNullException(nameof(observer));
  172. if (subscriptions == null)
  173. throw new ArgumentNullException(nameof(subscriptions));
  174. var gate = new AsyncLock();
  175. var winner = default(int?);
  176. var count = subscriptions.Length;
  177. async Task ElectWinnerAsync(int index)
  178. {
  179. winner = index;
  180. var dispose = new List<Task>(count - 1);
  181. for (var i = 0; i < count; i++)
  182. {
  183. if (i != index)
  184. {
  185. dispose.Add(subscriptions[i].DisposeAsync().AsTask());
  186. }
  187. }
  188. await Task.WhenAll(dispose).ConfigureAwait(false);
  189. }
  190. IAsyncObserver<TSource> CreateObserver(int index) =>
  191. Create<TSource>(
  192. async x =>
  193. {
  194. using (await gate.LockAsync().ConfigureAwait(false))
  195. {
  196. if (winner == null)
  197. {
  198. await ElectWinnerAsync(index).ConfigureAwait(false);
  199. }
  200. if (winner == index)
  201. {
  202. await observer.OnNextAsync(x).ConfigureAwait(false);
  203. }
  204. }
  205. },
  206. async ex =>
  207. {
  208. using (await gate.LockAsync().ConfigureAwait(false))
  209. {
  210. if (winner == null)
  211. {
  212. await ElectWinnerAsync(index).ConfigureAwait(false);
  213. }
  214. if (winner == index)
  215. {
  216. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  217. }
  218. }
  219. },
  220. async () =>
  221. {
  222. using (await gate.LockAsync().ConfigureAwait(false))
  223. {
  224. if (winner == null)
  225. {
  226. await ElectWinnerAsync(index).ConfigureAwait(false);
  227. }
  228. if (winner == index)
  229. {
  230. await observer.OnCompletedAsync().ConfigureAwait(false);
  231. }
  232. }
  233. }
  234. );
  235. var res = new IAsyncObserver<TSource>[count];
  236. for (var i = 0; i < count; i++)
  237. {
  238. res[i] = CreateObserver(i);
  239. }
  240. return res;
  241. }
  242. private enum AmbState
  243. {
  244. None,
  245. First,
  246. Second,
  247. }
  248. }
  249. }