QueryLanguageEx.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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.Linq;
  6. using System.Reactive.Concurrency;
  7. using System.Reactive.Disposables;
  8. using System.Reactive.Subjects;
  9. namespace System.Reactive.Linq
  10. {
  11. internal class QueryLanguageEx : IQueryLanguageEx
  12. {
  13. #region Create
  14. public virtual IObservable<TResult> Create<TResult>(Func<IObserver<TResult>, IEnumerable<IObservable<object>>> iteratorMethod)
  15. {
  16. return new AnonymousObservable<TResult>(observer =>
  17. iteratorMethod(observer).Concat().Subscribe(_ => { }, observer.OnError, observer.OnCompleted));
  18. }
  19. public virtual IObservable<Unit> Create(Func<IEnumerable<IObservable<object>>> iteratorMethod)
  20. {
  21. return new AnonymousObservable<Unit>(observer =>
  22. iteratorMethod().Concat().Subscribe(_ => { }, observer.OnError, observer.OnCompleted));
  23. }
  24. #endregion
  25. #region Expand
  26. public virtual IObservable<TSource> Expand<TSource>(IObservable<TSource> source, Func<TSource, IObservable<TSource>> selector, IScheduler scheduler)
  27. {
  28. return new AnonymousObservable<TSource>(observer =>
  29. {
  30. var outGate = new object();
  31. var q = new Queue<IObservable<TSource>>();
  32. var m = new SerialDisposable();
  33. var d = new CompositeDisposable { m };
  34. var activeCount = 0;
  35. var isAcquired = false;
  36. var ensureActive = default(Action);
  37. ensureActive = () =>
  38. {
  39. var isOwner = false;
  40. lock (q)
  41. {
  42. if (q.Count > 0)
  43. {
  44. isOwner = !isAcquired;
  45. isAcquired = true;
  46. }
  47. }
  48. if (isOwner)
  49. {
  50. m.Disposable = scheduler.Schedule(self =>
  51. {
  52. var work = default(IObservable<TSource>);
  53. lock (q)
  54. {
  55. if (q.Count > 0)
  56. work = q.Dequeue();
  57. else
  58. {
  59. isAcquired = false;
  60. return;
  61. }
  62. }
  63. var m1 = new SingleAssignmentDisposable();
  64. d.Add(m1);
  65. m1.Disposable = work.Subscribe(
  66. x =>
  67. {
  68. lock (outGate)
  69. observer.OnNext(x);
  70. var result = default(IObservable<TSource>);
  71. try
  72. {
  73. result = selector(x);
  74. }
  75. catch (Exception exception)
  76. {
  77. lock (outGate)
  78. observer.OnError(exception);
  79. }
  80. lock (q)
  81. {
  82. q.Enqueue(result);
  83. activeCount++;
  84. }
  85. ensureActive();
  86. },
  87. exception =>
  88. {
  89. lock (outGate)
  90. observer.OnError(exception);
  91. },
  92. () =>
  93. {
  94. d.Remove(m1);
  95. var done = false;
  96. lock (q)
  97. {
  98. activeCount--;
  99. if (activeCount == 0)
  100. done = true;
  101. }
  102. if (done)
  103. lock (outGate)
  104. observer.OnCompleted();
  105. });
  106. self();
  107. });
  108. }
  109. };
  110. lock (q)
  111. {
  112. q.Enqueue(source);
  113. activeCount++;
  114. }
  115. ensureActive();
  116. return d;
  117. });
  118. }
  119. public virtual IObservable<TSource> Expand<TSource>(IObservable<TSource> source, Func<TSource, IObservable<TSource>> selector)
  120. {
  121. return source.Expand(selector, SchedulerDefaults.Iteration);
  122. }
  123. #endregion
  124. #region ForkJoin
  125. public virtual IObservable<TResult> ForkJoin<TFirst, TSecond, TResult>(IObservable<TFirst> first, IObservable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
  126. {
  127. return Combine<TFirst, TSecond, TResult>(first, second, (observer, leftSubscription, rightSubscription) =>
  128. {
  129. var leftStopped = false;
  130. var rightStopped = false;
  131. var hasLeft = false;
  132. var hasRight = false;
  133. var lastLeft = default(TFirst);
  134. var lastRight = default(TSecond);
  135. return new BinaryObserver<TFirst, TSecond>(
  136. left =>
  137. {
  138. switch (left.Kind)
  139. {
  140. case NotificationKind.OnNext:
  141. hasLeft = true;
  142. lastLeft = left.Value;
  143. break;
  144. case NotificationKind.OnError:
  145. rightSubscription.Dispose();
  146. observer.OnError(left.Exception);
  147. break;
  148. case NotificationKind.OnCompleted:
  149. leftStopped = true;
  150. if (rightStopped)
  151. {
  152. if (!hasLeft)
  153. observer.OnCompleted();
  154. else if (!hasRight)
  155. observer.OnCompleted();
  156. else
  157. {
  158. TResult result;
  159. try
  160. {
  161. result = resultSelector(lastLeft, lastRight);
  162. }
  163. catch (Exception exception)
  164. {
  165. observer.OnError(exception);
  166. return;
  167. }
  168. observer.OnNext(result);
  169. observer.OnCompleted();
  170. }
  171. }
  172. break;
  173. }
  174. },
  175. right =>
  176. {
  177. switch (right.Kind)
  178. {
  179. case NotificationKind.OnNext:
  180. hasRight = true;
  181. lastRight = right.Value;
  182. break;
  183. case NotificationKind.OnError:
  184. leftSubscription.Dispose();
  185. observer.OnError(right.Exception);
  186. break;
  187. case NotificationKind.OnCompleted:
  188. rightStopped = true;
  189. if (leftStopped)
  190. {
  191. if (!hasLeft)
  192. observer.OnCompleted();
  193. else if (!hasRight)
  194. observer.OnCompleted();
  195. else
  196. {
  197. TResult result;
  198. try
  199. {
  200. result = resultSelector(lastLeft, lastRight);
  201. }
  202. catch (Exception exception)
  203. {
  204. observer.OnError(exception);
  205. return;
  206. }
  207. observer.OnNext(result);
  208. observer.OnCompleted();
  209. }
  210. }
  211. break;
  212. }
  213. });
  214. });
  215. }
  216. public virtual IObservable<TSource[]> ForkJoin<TSource>(params IObservable<TSource>[] sources)
  217. {
  218. return sources.ForkJoin();
  219. }
  220. public virtual IObservable<TSource[]> ForkJoin<TSource>(IEnumerable<IObservable<TSource>> sources)
  221. {
  222. return new AnonymousObservable<TSource[]>(subscriber =>
  223. {
  224. var allSources = sources.ToArray();
  225. var count = allSources.Length;
  226. if (count == 0)
  227. {
  228. subscriber.OnCompleted();
  229. return Disposable.Empty;
  230. }
  231. var group = new CompositeDisposable(allSources.Length);
  232. var gate = new object();
  233. var finished = false;
  234. var hasResults = new bool[count];
  235. var hasCompleted = new bool[count];
  236. var results = new List<TSource>(count);
  237. lock (gate)
  238. {
  239. for (var index = 0; index < count; index++)
  240. {
  241. var currentIndex = index;
  242. var source = allSources[index];
  243. results.Add(default(TSource));
  244. group.Add(source.Subscribe(
  245. value =>
  246. {
  247. lock (gate)
  248. {
  249. if (!finished)
  250. {
  251. hasResults[currentIndex] = true;
  252. results[currentIndex] = value;
  253. }
  254. }
  255. },
  256. error =>
  257. {
  258. lock (gate)
  259. {
  260. finished = true;
  261. subscriber.OnError(error);
  262. group.Dispose();
  263. }
  264. },
  265. () =>
  266. {
  267. lock (gate)
  268. {
  269. if (!finished)
  270. {
  271. if (!hasResults[currentIndex])
  272. {
  273. subscriber.OnCompleted();
  274. return;
  275. }
  276. hasCompleted[currentIndex] = true;
  277. foreach (var completed in hasCompleted)
  278. {
  279. if (!completed)
  280. return;
  281. }
  282. finished = true;
  283. subscriber.OnNext(results.ToArray());
  284. subscriber.OnCompleted();
  285. }
  286. }
  287. }));
  288. }
  289. }
  290. return group;
  291. });
  292. }
  293. #endregion
  294. #region Let
  295. public virtual IObservable<TResult> Let<TSource, TResult>(IObservable<TSource> source, Func<IObservable<TSource>, IObservable<TResult>> function)
  296. {
  297. return function(source);
  298. }
  299. #endregion
  300. #region ManySelect
  301. public virtual IObservable<TResult> ManySelect<TSource, TResult>(IObservable<TSource> source, Func<IObservable<TSource>, TResult> selector)
  302. {
  303. return ManySelect(source, selector, DefaultScheduler.Instance);
  304. }
  305. public virtual IObservable<TResult> ManySelect<TSource, TResult>(IObservable<TSource> source, Func<IObservable<TSource>, TResult> selector, IScheduler scheduler)
  306. {
  307. return Observable.Defer<TResult>(() =>
  308. {
  309. var chain = default(ChainObservable<TSource>);
  310. return source
  311. .Select(
  312. x =>
  313. {
  314. var curr = new ChainObservable<TSource>(x);
  315. if (chain != null)
  316. chain.OnNext(curr);
  317. chain = curr;
  318. return (IObservable<TSource>)curr;
  319. })
  320. .Do(
  321. _ => { },
  322. exception =>
  323. {
  324. if (chain != null)
  325. chain.OnError(exception);
  326. },
  327. () =>
  328. {
  329. if (chain != null)
  330. chain.OnCompleted();
  331. })
  332. .ObserveOn(scheduler)
  333. .Select(selector);
  334. });
  335. }
  336. class ChainObservable<T> : ISubject<IObservable<T>, T>
  337. {
  338. T head;
  339. AsyncSubject<IObservable<T>> tail = new AsyncSubject<IObservable<T>>();
  340. public ChainObservable(T head)
  341. {
  342. this.head = head;
  343. }
  344. public IDisposable Subscribe(IObserver<T> observer)
  345. {
  346. var g = new CompositeDisposable();
  347. g.Add(CurrentThreadScheduler.Instance.Schedule(() =>
  348. {
  349. observer.OnNext(head);
  350. g.Add(tail.Merge().Subscribe(observer));
  351. }));
  352. return g;
  353. }
  354. public void OnCompleted()
  355. {
  356. OnNext(Observable.Empty<T>());
  357. }
  358. public void OnError(Exception error)
  359. {
  360. OnNext(Observable.Throw<T>(error));
  361. }
  362. public void OnNext(IObservable<T> value)
  363. {
  364. tail.OnNext(value);
  365. tail.OnCompleted();
  366. }
  367. }
  368. #endregion
  369. #region ToListObservable
  370. public virtual ListObservable<TSource> ToListObservable<TSource>(IObservable<TSource> source)
  371. {
  372. return new ListObservable<TSource>(source);
  373. }
  374. #endregion
  375. #region |> Helpers <|
  376. private static IObservable<TResult> Combine<TLeft, TRight, TResult>(IObservable<TLeft> leftSource, IObservable<TRight> rightSource, Func<IObserver<TResult>, IDisposable, IDisposable, IObserver<Either<Notification<TLeft>, Notification<TRight>>>> combinerSelector)
  377. {
  378. return new AnonymousObservable<TResult>(observer =>
  379. {
  380. var leftSubscription = new SingleAssignmentDisposable();
  381. var rightSubscription = new SingleAssignmentDisposable();
  382. var combiner = combinerSelector(observer, leftSubscription, rightSubscription);
  383. var gate = new object();
  384. leftSubscription.Disposable = leftSource.Materialize().Select(x => Either<Notification<TLeft>, Notification<TRight>>.CreateLeft(x)).Synchronize(gate).Subscribe(combiner);
  385. rightSubscription.Disposable = rightSource.Materialize().Select(x => Either<Notification<TLeft>, Notification<TRight>>.CreateRight(x)).Synchronize(gate).Subscribe(combiner);
  386. return StableCompositeDisposable.Create(leftSubscription, rightSubscription);
  387. });
  388. }
  389. #endregion
  390. }
  391. }