Zip.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reactive.Disposables;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. #region Binary
  11. internal static class Zip<TFirst, TSecond, TResult>
  12. {
  13. internal sealed class Observable : Producer<TResult, Observable._>
  14. {
  15. private readonly IObservable<TFirst> _first;
  16. private readonly IObservable<TSecond> _second;
  17. private readonly Func<TFirst, TSecond, TResult> _resultSelector;
  18. public Observable(IObservable<TFirst> first, IObservable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
  19. {
  20. _first = first;
  21. _second = second;
  22. _resultSelector = resultSelector;
  23. }
  24. protected override _ CreateSink(IObserver<TResult> observer, IDisposable cancel) => new _(_resultSelector, observer, cancel);
  25. protected override IDisposable Run(_ sink) => sink.Run(_first, _second);
  26. internal sealed class _ : Sink<TResult>
  27. {
  28. private readonly Func<TFirst, TSecond, TResult> _resultSelector;
  29. public _(Func<TFirst, TSecond, TResult> resultSelector, IObserver<TResult> observer, IDisposable cancel)
  30. : base(observer, cancel)
  31. {
  32. _resultSelector = resultSelector;
  33. }
  34. private object _gate;
  35. public IDisposable Run(IObservable<TFirst> first, IObservable<TSecond> second)
  36. {
  37. _gate = new object();
  38. var fstSubscription = new SingleAssignmentDisposable();
  39. var sndSubscription = new SingleAssignmentDisposable();
  40. var fstO = new FirstObserver(this, fstSubscription);
  41. var sndO = new SecondObserver(this, sndSubscription);
  42. fstO.Other = sndO;
  43. sndO.Other = fstO;
  44. fstSubscription.Disposable = first.SubscribeSafe(fstO);
  45. sndSubscription.Disposable = second.SubscribeSafe(sndO);
  46. return StableCompositeDisposable.Create(fstSubscription, sndSubscription, fstO, sndO);
  47. }
  48. private sealed class FirstObserver : IObserver<TFirst>, IDisposable
  49. {
  50. private readonly _ _parent;
  51. private readonly IDisposable _self;
  52. private SecondObserver _other;
  53. private Queue<TFirst> _queue;
  54. public FirstObserver(_ parent, IDisposable self)
  55. {
  56. _parent = parent;
  57. _self = self;
  58. _queue = new Queue<TFirst>();
  59. }
  60. public SecondObserver Other { set { _other = value; } }
  61. public Queue<TFirst> Queue => _queue;
  62. public bool Done { get; private set; }
  63. public void OnNext(TFirst value)
  64. {
  65. lock (_parent._gate)
  66. {
  67. if (_other.Queue.Count > 0)
  68. {
  69. var r = _other.Queue.Dequeue();
  70. var res = default(TResult);
  71. try
  72. {
  73. res = _parent._resultSelector(value, r);
  74. }
  75. catch (Exception ex)
  76. {
  77. _parent._observer.OnError(ex);
  78. _parent.Dispose();
  79. return;
  80. }
  81. _parent._observer.OnNext(res);
  82. }
  83. else
  84. {
  85. if (_other.Done)
  86. {
  87. _parent._observer.OnCompleted();
  88. _parent.Dispose();
  89. return;
  90. }
  91. _queue.Enqueue(value);
  92. }
  93. }
  94. }
  95. public void OnError(Exception error)
  96. {
  97. lock (_parent._gate)
  98. {
  99. _parent._observer.OnError(error);
  100. _parent.Dispose();
  101. }
  102. }
  103. public void OnCompleted()
  104. {
  105. lock (_parent._gate)
  106. {
  107. Done = true;
  108. if (_other.Done)
  109. {
  110. _parent._observer.OnCompleted();
  111. _parent.Dispose();
  112. return;
  113. }
  114. else
  115. {
  116. _self.Dispose();
  117. }
  118. }
  119. }
  120. public void Dispose()
  121. {
  122. _queue.Clear();
  123. }
  124. }
  125. private sealed class SecondObserver : IObserver<TSecond>, IDisposable
  126. {
  127. private readonly _ _parent;
  128. private readonly IDisposable _self;
  129. private FirstObserver _other;
  130. private Queue<TSecond> _queue;
  131. public SecondObserver(_ parent, IDisposable self)
  132. {
  133. _parent = parent;
  134. _self = self;
  135. _queue = new Queue<TSecond>();
  136. }
  137. public FirstObserver Other { set { _other = value; } }
  138. public Queue<TSecond> Queue => _queue;
  139. public bool Done { get; private set; }
  140. public void OnNext(TSecond value)
  141. {
  142. lock (_parent._gate)
  143. {
  144. if (_other.Queue.Count > 0)
  145. {
  146. var l = _other.Queue.Dequeue();
  147. var res = default(TResult);
  148. try
  149. {
  150. res = _parent._resultSelector(l, value);
  151. }
  152. catch (Exception ex)
  153. {
  154. _parent._observer.OnError(ex);
  155. _parent.Dispose();
  156. return;
  157. }
  158. _parent._observer.OnNext(res);
  159. }
  160. else
  161. {
  162. if (_other.Done)
  163. {
  164. _parent._observer.OnCompleted();
  165. _parent.Dispose();
  166. return;
  167. }
  168. _queue.Enqueue(value);
  169. }
  170. }
  171. }
  172. public void OnError(Exception error)
  173. {
  174. lock (_parent._gate)
  175. {
  176. _parent._observer.OnError(error);
  177. _parent.Dispose();
  178. }
  179. }
  180. public void OnCompleted()
  181. {
  182. lock (_parent._gate)
  183. {
  184. Done = true;
  185. if (_other.Done)
  186. {
  187. _parent._observer.OnCompleted();
  188. _parent.Dispose();
  189. return;
  190. }
  191. else
  192. {
  193. _self.Dispose();
  194. }
  195. }
  196. }
  197. public void Dispose()
  198. {
  199. _queue.Clear();
  200. }
  201. }
  202. }
  203. }
  204. internal sealed class Enumerable : Producer<TResult, Enumerable._>
  205. {
  206. private readonly IObservable<TFirst> _first;
  207. private readonly IEnumerable<TSecond> _second;
  208. private readonly Func<TFirst, TSecond, TResult> _resultSelector;
  209. public Enumerable(IObservable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
  210. {
  211. _first = first;
  212. _second = second;
  213. _resultSelector = resultSelector;
  214. }
  215. protected override _ CreateSink(IObserver<TResult> observer, IDisposable cancel) => new _(_resultSelector, observer, cancel);
  216. protected override IDisposable Run(_ sink) => sink.Run(_first, _second);
  217. internal sealed class _ : Sink<TResult>, IObserver<TFirst>
  218. {
  219. private readonly Func<TFirst, TSecond, TResult> _resultSelector;
  220. public _(Func<TFirst, TSecond, TResult> resultSelector, IObserver<TResult> observer, IDisposable cancel)
  221. : base(observer, cancel)
  222. {
  223. _resultSelector = resultSelector;
  224. }
  225. private IEnumerator<TSecond> _rightEnumerator;
  226. public IDisposable Run(IObservable<TFirst> first, IEnumerable<TSecond> second)
  227. {
  228. //
  229. // Notice the evaluation order of obtaining the enumerator and subscribing to the
  230. // observable sequence is reversed compared to the operator's signature. This is
  231. // required to make sure the enumerator is available as soon as the observer can
  232. // be called. Otherwise, we end up having a race for the initialization and use
  233. // of the _rightEnumerator field.
  234. //
  235. try
  236. {
  237. _rightEnumerator = second.GetEnumerator();
  238. }
  239. catch (Exception exception)
  240. {
  241. base._observer.OnError(exception);
  242. base.Dispose();
  243. return Disposable.Empty;
  244. }
  245. var leftSubscription = first.SubscribeSafe(this);
  246. return StableCompositeDisposable.Create(leftSubscription, _rightEnumerator);
  247. }
  248. public void OnNext(TFirst value)
  249. {
  250. var hasNext = false;
  251. try
  252. {
  253. hasNext = _rightEnumerator.MoveNext();
  254. }
  255. catch (Exception ex)
  256. {
  257. base._observer.OnError(ex);
  258. base.Dispose();
  259. return;
  260. }
  261. if (hasNext)
  262. {
  263. var right = default(TSecond);
  264. try
  265. {
  266. right = _rightEnumerator.Current;
  267. }
  268. catch (Exception ex)
  269. {
  270. base._observer.OnError(ex);
  271. base.Dispose();
  272. return;
  273. }
  274. TResult result;
  275. try
  276. {
  277. result = _resultSelector(value, right);
  278. }
  279. catch (Exception ex)
  280. {
  281. base._observer.OnError(ex);
  282. base.Dispose();
  283. return;
  284. }
  285. base._observer.OnNext(result);
  286. }
  287. else
  288. {
  289. base._observer.OnCompleted();
  290. base.Dispose();
  291. }
  292. }
  293. public void OnError(Exception error)
  294. {
  295. base._observer.OnError(error);
  296. base.Dispose();
  297. }
  298. public void OnCompleted()
  299. {
  300. base._observer.OnCompleted();
  301. base.Dispose();
  302. }
  303. }
  304. }
  305. }
  306. #endregion
  307. #region [3,16]-ary
  308. #region Helpers for n-ary overloads
  309. internal interface IZip
  310. {
  311. void Next(int index);
  312. void Fail(Exception error);
  313. void Done(int index);
  314. }
  315. internal abstract class ZipSink<TResult> : Sink<TResult>, IZip
  316. {
  317. protected readonly object _gate;
  318. private readonly ICollection[] _queues;
  319. private readonly bool[] _isDone;
  320. public ZipSink(int arity, IObserver<TResult> observer, IDisposable cancel)
  321. : base(observer, cancel)
  322. {
  323. _gate = new object();
  324. _isDone = new bool[arity];
  325. _queues = new ICollection[arity];
  326. }
  327. public ICollection[] Queues => _queues;
  328. public void Next(int index)
  329. {
  330. var hasValueAll = true;
  331. foreach (var queue in _queues)
  332. {
  333. if (queue.Count == 0)
  334. {
  335. hasValueAll = false;
  336. break;
  337. }
  338. }
  339. if (hasValueAll)
  340. {
  341. var res = default(TResult);
  342. try
  343. {
  344. res = GetResult();
  345. }
  346. catch (Exception ex)
  347. {
  348. base._observer.OnError(ex);
  349. base.Dispose();
  350. return;
  351. }
  352. base._observer.OnNext(res);
  353. }
  354. else
  355. {
  356. var allOthersDone = true;
  357. for (int i = 0; i < _isDone.Length; i++)
  358. {
  359. if (i != index && !_isDone[i])
  360. {
  361. allOthersDone = false;
  362. break;
  363. }
  364. }
  365. if (allOthersDone)
  366. {
  367. base._observer.OnCompleted();
  368. base.Dispose();
  369. }
  370. }
  371. }
  372. protected abstract TResult GetResult();
  373. public void Fail(Exception error)
  374. {
  375. base._observer.OnError(error);
  376. base.Dispose();
  377. }
  378. public void Done(int index)
  379. {
  380. _isDone[index] = true;
  381. var allDone = true;
  382. foreach (var isDone in _isDone)
  383. {
  384. if (!isDone)
  385. {
  386. allDone = false;
  387. break;
  388. }
  389. }
  390. if (allDone)
  391. {
  392. base._observer.OnCompleted();
  393. base.Dispose();
  394. return;
  395. }
  396. }
  397. }
  398. internal sealed class ZipObserver<T> : IObserver<T>
  399. {
  400. private readonly object _gate;
  401. private readonly IZip _parent;
  402. private readonly int _index;
  403. private readonly IDisposable _self;
  404. private readonly Queue<T> _values;
  405. public ZipObserver(object gate, IZip parent, int index, IDisposable self)
  406. {
  407. _gate = gate;
  408. _parent = parent;
  409. _index = index;
  410. _self = self;
  411. _values = new Queue<T>();
  412. }
  413. public Queue<T> Values => _values;
  414. public void OnNext(T value)
  415. {
  416. lock (_gate)
  417. {
  418. _values.Enqueue(value);
  419. _parent.Next(_index);
  420. }
  421. }
  422. public void OnError(Exception error)
  423. {
  424. _self.Dispose();
  425. lock (_gate)
  426. {
  427. _parent.Fail(error);
  428. }
  429. }
  430. public void OnCompleted()
  431. {
  432. _self.Dispose();
  433. lock (_gate)
  434. {
  435. _parent.Done(_index);
  436. }
  437. }
  438. }
  439. #endregion
  440. #endregion
  441. #region N-ary
  442. internal sealed class Zip<TSource> : Producer<IList<TSource>, Zip<TSource>._>
  443. {
  444. private readonly IEnumerable<IObservable<TSource>> _sources;
  445. public Zip(IEnumerable<IObservable<TSource>> sources)
  446. {
  447. _sources = sources;
  448. }
  449. protected override _ CreateSink(IObserver<IList<TSource>> observer, IDisposable cancel) => new _(this, observer, cancel);
  450. protected override IDisposable Run(_ sink) => sink.Run();
  451. internal sealed class _ : Sink<IList<TSource>>
  452. {
  453. private readonly Zip<TSource> _parent;
  454. public _(Zip<TSource> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
  455. : base(observer, cancel)
  456. {
  457. _parent = parent;
  458. }
  459. private object _gate;
  460. private Queue<TSource>[] _queues;
  461. private bool[] _isDone;
  462. private IDisposable[] _subscriptions;
  463. public IDisposable Run()
  464. {
  465. var srcs = _parent._sources.ToArray();
  466. var N = srcs.Length;
  467. _queues = new Queue<TSource>[N];
  468. for (int i = 0; i < N; i++)
  469. _queues[i] = new Queue<TSource>();
  470. _isDone = new bool[N];
  471. _subscriptions = new SingleAssignmentDisposable[N];
  472. _gate = new object();
  473. for (int i = 0; i < N; i++)
  474. {
  475. var j = i;
  476. var d = new SingleAssignmentDisposable();
  477. _subscriptions[j] = d;
  478. var o = new SourceObserver(this, j);
  479. d.Disposable = srcs[j].SubscribeSafe(o);
  480. }
  481. return new CompositeDisposable(_subscriptions) { Disposable.Create(() => { foreach (var q in _queues) q.Clear(); }) };
  482. }
  483. private void OnNext(int index, TSource value)
  484. {
  485. lock (_gate)
  486. {
  487. _queues[index].Enqueue(value);
  488. if (_queues.All(q => q.Count > 0))
  489. {
  490. var n = _queues.Length;
  491. var res = new List<TSource>(n);
  492. for (var i = 0; i < n; i++)
  493. {
  494. res.Add(_queues[i].Dequeue());
  495. }
  496. base._observer.OnNext(res);
  497. }
  498. else if (_isDone.AllExcept(index))
  499. {
  500. base._observer.OnCompleted();
  501. base.Dispose();
  502. return;
  503. }
  504. }
  505. }
  506. private void OnError(Exception error)
  507. {
  508. lock (_gate)
  509. {
  510. base._observer.OnError(error);
  511. base.Dispose();
  512. }
  513. }
  514. private void OnCompleted(int index)
  515. {
  516. lock (_gate)
  517. {
  518. _isDone[index] = true;
  519. if (_isDone.All())
  520. {
  521. base._observer.OnCompleted();
  522. base.Dispose();
  523. return;
  524. }
  525. else
  526. {
  527. _subscriptions[index].Dispose();
  528. }
  529. }
  530. }
  531. private sealed class SourceObserver : IObserver<TSource>
  532. {
  533. private readonly _ _parent;
  534. private readonly int _index;
  535. public SourceObserver(_ parent, int index)
  536. {
  537. _parent = parent;
  538. _index = index;
  539. }
  540. public void OnNext(TSource value)
  541. {
  542. _parent.OnNext(_index, value);
  543. }
  544. public void OnError(Exception error)
  545. {
  546. _parent.OnError(error);
  547. }
  548. public void OnCompleted()
  549. {
  550. _parent.OnCompleted(_index);
  551. }
  552. }
  553. }
  554. }
  555. #endregion
  556. }