1
0

OrderBy.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Reactive.Disposables;
  7. using System.Reactive.Subjects;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. class OrderBy<TSource, TKey> : OrderedProducer<TSource>, IOrderedObservable<TSource>
  11. {
  12. private readonly Func<TSource, IObservable<TKey>> _timeSelector;
  13. private readonly Func<TSource, TKey> _keySelector;
  14. private readonly IComparer<TKey> _comparer;
  15. private readonly bool _descending;
  16. public OrderBy(IObservable<TSource> source, Func<TSource, IObservable<TKey>> timeSelector, bool descending)
  17. : base(source, null)
  18. {
  19. _timeSelector = timeSelector;
  20. _descending = descending;
  21. }
  22. public OrderBy(IObservable<TSource> source, Func<TSource, IObservable<TKey>> timeSelector, bool descending, OrderedProducer<TSource> previous)
  23. : base(source, previous)
  24. {
  25. _timeSelector = timeSelector;
  26. _descending = descending;
  27. }
  28. public OrderBy(IObservable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer, bool descending)
  29. : base(source, null)
  30. {
  31. _keySelector = keySelector;
  32. _comparer = comparer ?? Comparer<TKey>.Default;
  33. _descending = descending;
  34. }
  35. public OrderBy(IObservable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer, bool descending, OrderedProducer<TSource> previous)
  36. : base(source, previous)
  37. {
  38. _keySelector = keySelector;
  39. _comparer = comparer ?? Comparer<TKey>.Default;
  40. _descending = descending;
  41. }
  42. public IOrderedObservable<TSource> CreateOrderedObservable<TTKey>(Func<TSource, TTKey> keySelector, IComparer<TTKey> comparer, bool descending)
  43. {
  44. return new OrderBy<TSource, TTKey>(base._source, keySelector, comparer, descending, previous: this);
  45. }
  46. public IOrderedObservable<TSource> CreateOrderedObservable<TOther>(Func<TSource, IObservable<TOther>> timeSelector, bool descending)
  47. {
  48. return new OrderBy<TSource, TOther>(base._source, timeSelector, descending, previous: this);
  49. }
  50. protected override SortSink Sort(IObserver<TSource> observer, IDisposable cancel)
  51. {
  52. if (_timeSelector != null)
  53. {
  54. if (_descending)
  55. {
  56. return new Descending(this, observer, cancel);
  57. }
  58. else
  59. {
  60. return new Ascending(this, observer, cancel);
  61. }
  62. }
  63. else
  64. {
  65. var sink = observer as ι;
  66. if (sink != null)
  67. {
  68. /* This optimization exists for 2 reasons:
  69. *
  70. * 1. To avoid having to use multiple buffers in consecutive ordering operations.
  71. * 2. To take advantage of Enumerable's optimizations for consecutive ordering operations.
  72. */
  73. sink.OrderBy(this);
  74. return sink;
  75. }
  76. else
  77. {
  78. if (_descending)
  79. {
  80. return new Descending_(this, observer, cancel);
  81. }
  82. else
  83. {
  84. return new Ascending_(this, observer, cancel);
  85. }
  86. }
  87. }
  88. }
  89. class Ascending : ρ
  90. {
  91. public Ascending(OrderBy<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  92. : base(parent, observer, cancel)
  93. {
  94. }
  95. protected override void Consume(TSource value)
  96. {
  97. base._observer.OnNext(value);
  98. }
  99. protected override void Complete()
  100. {
  101. base._observer.OnCompleted();
  102. }
  103. }
  104. class Descending : ρ
  105. {
  106. public Descending(OrderBy<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  107. : base(parent, observer, cancel)
  108. {
  109. }
  110. private IList<TSource> _list;
  111. public override IDisposable Initialize()
  112. {
  113. _list = new List<TSource>();
  114. return base.Initialize();
  115. }
  116. protected override void Consume(TSource value)
  117. {
  118. _list.Add(value);
  119. }
  120. protected override void Complete()
  121. {
  122. foreach (var value in _list.Reverse())
  123. {
  124. base._observer.OnNext(value);
  125. }
  126. base._observer.OnCompleted();
  127. }
  128. }
  129. class Ascending_ : ι
  130. {
  131. public Ascending_(OrderBy<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  132. : base(parent, observer, cancel)
  133. {
  134. }
  135. protected override IOrderedEnumerable<TSource> OrderBy(IEnumerable<TSource> source)
  136. {
  137. return source.OrderBy(_parent._keySelector, _parent._comparer);
  138. }
  139. protected override IOrderedEnumerable<TSource> ThenBy(IOrderedEnumerable<TSource> source)
  140. {
  141. return source.ThenBy(_parent._keySelector, _parent._comparer);
  142. }
  143. }
  144. class Descending_ : ι
  145. {
  146. public Descending_(OrderBy<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  147. : base(parent, observer, cancel)
  148. {
  149. }
  150. protected override IOrderedEnumerable<TSource> OrderBy(IEnumerable<TSource> source)
  151. {
  152. return source.OrderByDescending(base._parent._keySelector, base._parent._comparer);
  153. }
  154. protected override IOrderedEnumerable<TSource> ThenBy(IOrderedEnumerable<TSource> source)
  155. {
  156. return source.ThenByDescending(base._parent._keySelector, base._parent._comparer);
  157. }
  158. }
  159. /// <summary>
  160. /// Reactive sorting. This code is based on the code from the SelectMany operator (8/11/2013).
  161. /// </summary>
  162. abstract class ρ : SortSink
  163. {
  164. protected readonly OrderBy<TSource, TKey> _parent;
  165. public ρ(OrderBy<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  166. : base(observer, cancel)
  167. {
  168. _parent = parent;
  169. }
  170. private object _gate;
  171. private bool _isStopped;
  172. private CompositeDisposable _group;
  173. private SingleAssignmentDisposable _sourceSubscription;
  174. public override IDisposable Initialize()
  175. {
  176. _gate = new object();
  177. _isStopped = false;
  178. _group = new CompositeDisposable();
  179. _sourceSubscription = new SingleAssignmentDisposable();
  180. _group.Add(_sourceSubscription);
  181. return _group;
  182. }
  183. public override void Run(IObservable<TSource> source)
  184. {
  185. _sourceSubscription.Disposable = source.SubscribeSafe(this);
  186. }
  187. public override void OnNext(TSource value)
  188. {
  189. var collection = default(IObservable<TKey>);
  190. try
  191. {
  192. collection = _parent._timeSelector(value);
  193. }
  194. catch (Exception ex)
  195. {
  196. lock (_gate)
  197. {
  198. base._observer.OnError(ex);
  199. base.Dispose();
  200. }
  201. return;
  202. }
  203. var innerSubscription = new SingleAssignmentDisposable();
  204. _group.Add(innerSubscription);
  205. innerSubscription.Disposable = collection.SubscribeSafe(new ι(this, value, innerSubscription));
  206. }
  207. public override void OnError(Exception error)
  208. {
  209. lock (_gate)
  210. {
  211. base._observer.OnError(error);
  212. base.Dispose();
  213. }
  214. }
  215. public override void OnCompleted()
  216. {
  217. _isStopped = true;
  218. if (_group.Count == 1)
  219. {
  220. //
  221. // Notice there can be a race between OnCompleted of the source and any
  222. // of the inner sequences, where both see _group.Count == 1, and one is
  223. // waiting for the lock. There won't be a double OnCompleted observation
  224. // though, because the call to Dispose silences the observer by swapping
  225. // in a NopObserver<T>.
  226. //
  227. lock (_gate)
  228. {
  229. Complete();
  230. base.Dispose();
  231. }
  232. }
  233. else
  234. {
  235. _sourceSubscription.Dispose();
  236. }
  237. }
  238. protected abstract void Complete();
  239. protected abstract void Consume(TSource value);
  240. class ι : IObserver<TKey>
  241. {
  242. private readonly ρ _parent;
  243. private readonly TSource _value;
  244. private readonly IDisposable _self;
  245. public ι(ρ parent, TSource value, IDisposable self)
  246. {
  247. _parent = parent;
  248. _value = value;
  249. _self = self;
  250. }
  251. public void OnNext(TKey value)
  252. {
  253. OnCompleted();
  254. }
  255. public void OnError(Exception error)
  256. {
  257. lock (_parent._gate)
  258. {
  259. _parent._observer.OnError(error);
  260. _parent.Dispose();
  261. }
  262. }
  263. public void OnCompleted()
  264. {
  265. lock (_parent._gate)
  266. {
  267. _parent.Consume(_value);
  268. }
  269. _parent._group.Remove(_self);
  270. if (_parent._isStopped && _parent._group.Count == 1)
  271. {
  272. //
  273. // Notice there can be a race between OnCompleted of the source and any
  274. // of the inner sequences, where both see _group.Count == 1, and one is
  275. // waiting for the lock. There won't be a double OnCompleted observation
  276. // though, because the call to Dispose silences the observer by swapping
  277. // in a NopObserver<T>.
  278. //
  279. lock (_parent._gate)
  280. {
  281. _parent.Complete();
  282. _parent.Dispose();
  283. }
  284. }
  285. }
  286. }
  287. }
  288. /// <summary>
  289. /// Aggregates before sorting. This code is based on the code from the ToList operator (8/11/2013).
  290. /// </summary>
  291. abstract class ι : SortSink
  292. {
  293. protected readonly OrderBy<TSource, TKey> _parent;
  294. public ι(OrderBy<TSource, TKey> parent, IObserver<TSource> observer, IDisposable cancel)
  295. : base(observer, cancel)
  296. {
  297. _parent = parent;
  298. }
  299. private List<TSource> _list;
  300. private Stack<OrderBy<TSource, TKey>> _orderBy;
  301. private SingleAssignmentDisposable _sourceSubscription;
  302. public override IDisposable Initialize()
  303. {
  304. _list = new List<TSource>();
  305. _orderBy = new Stack<OrderBy<TSource, TKey>>();
  306. _sourceSubscription = new SingleAssignmentDisposable();
  307. return _sourceSubscription;
  308. }
  309. public override void Run(IObservable<TSource> source)
  310. {
  311. _sourceSubscription.Disposable = source.SubscribeSafe(this);
  312. }
  313. public override void OnNext(TSource value)
  314. {
  315. _list.Add(value);
  316. }
  317. public override void OnError(Exception error)
  318. {
  319. base._observer.OnError(error);
  320. base.Dispose();
  321. }
  322. public override void OnCompleted()
  323. {
  324. foreach (var value in OrderAll(_list))
  325. {
  326. base._observer.OnNext(value);
  327. }
  328. base._observer.OnCompleted();
  329. base.Dispose();
  330. }
  331. protected abstract IOrderedEnumerable<TSource> OrderBy(IEnumerable<TSource> source);
  332. protected abstract IOrderedEnumerable<TSource> ThenBy(IOrderedEnumerable<TSource> source);
  333. internal void OrderBy(OrderBy<TSource, TKey> parent)
  334. {
  335. _orderBy.Push(parent);
  336. }
  337. private IEnumerable<TSource> OrderAll(IEnumerable<TSource> source)
  338. {
  339. IOrderedEnumerable<TSource> ordered = null;
  340. foreach (var parent in _orderBy)
  341. {
  342. if (ordered == null)
  343. {
  344. ordered = parent._descending
  345. ? source.OrderByDescending(parent._keySelector, parent._comparer)
  346. : source.OrderBy(parent._keySelector, parent._comparer);
  347. }
  348. else
  349. {
  350. ordered = parent._descending
  351. ? ordered.ThenByDescending(parent._keySelector, parent._comparer)
  352. : ordered.ThenBy(parent._keySelector, parent._comparer);
  353. }
  354. }
  355. return ordered == null ? OrderBy(source) : ThenBy(ordered);
  356. }
  357. }
  358. }
  359. }