JoinObserver.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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.Reactive.Disposables;
  6. using System.Reactive.Linq;
  7. namespace System.Reactive.Joins
  8. {
  9. internal interface IJoinObserver : IDisposable
  10. {
  11. void Subscribe(object gate);
  12. void Dequeue();
  13. }
  14. internal sealed class JoinObserver<T> : ObserverBase<Notification<T>>, IJoinObserver
  15. {
  16. private object _gate;
  17. private readonly IObservable<T> _source;
  18. private readonly Action<Exception> _onError;
  19. private readonly List<ActivePlan> _activePlans;
  20. public Queue<Notification<T>> Queue { get; }
  21. private IDisposable _subscription;
  22. private bool _isDisposed;
  23. public JoinObserver(IObservable<T> source, Action<Exception> onError)
  24. {
  25. _source = source;
  26. _onError = onError;
  27. Queue = new Queue<Notification<T>>();
  28. _activePlans = new List<ActivePlan>();
  29. }
  30. public void AddActivePlan(ActivePlan activePlan)
  31. {
  32. _activePlans.Add(activePlan);
  33. }
  34. public void Subscribe(object gate)
  35. {
  36. _gate = gate;
  37. Disposable.SetSingle(ref _subscription, _source.Materialize().SubscribeSafe(this));
  38. }
  39. public void Dequeue()
  40. {
  41. Queue.Dequeue();
  42. }
  43. protected override void OnNextCore(Notification<T> notification)
  44. {
  45. lock (_gate)
  46. {
  47. if (!_isDisposed)
  48. {
  49. if (notification.Kind == NotificationKind.OnError)
  50. {
  51. _onError(notification.Exception);
  52. return;
  53. }
  54. Queue.Enqueue(notification);
  55. foreach (var activePlan in _activePlans.ToArray()) // Working on a copy since _activePlans might change while iterating.
  56. {
  57. activePlan.Match();
  58. }
  59. }
  60. }
  61. }
  62. protected override void OnErrorCore(Exception exception)
  63. {
  64. }
  65. protected override void OnCompletedCore()
  66. {
  67. }
  68. internal void RemoveActivePlan(ActivePlan activePlan)
  69. {
  70. _activePlans.Remove(activePlan);
  71. if (_activePlans.Count == 0)
  72. {
  73. Dispose();
  74. }
  75. }
  76. protected override void Dispose(bool disposing)
  77. {
  78. base.Dispose(disposing);
  79. if (!_isDisposed)
  80. {
  81. if (disposing)
  82. {
  83. Disposable.TryDispose(ref _subscription);
  84. }
  85. _isDisposed = true;
  86. }
  87. }
  88. }
  89. }