Zip.cs 22 KB

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