JoinObserver.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 List<ActivePlan> activePlans;
  20. public Queue<Notification<T>> Queue { get; private set; }
  21. private readonly SingleAssignmentDisposable subscription;
  22. private bool isDisposed;
  23. public JoinObserver(IObservable<T> source, Action<Exception> onError)
  24. {
  25. this.source = source;
  26. this.onError = onError;
  27. Queue = new Queue<Notification<T>>();
  28. subscription = new SingleAssignmentDisposable();
  29. activePlans = new List<ActivePlan>();
  30. }
  31. public void AddActivePlan(ActivePlan activePlan)
  32. {
  33. activePlans.Add(activePlan);
  34. }
  35. public void Subscribe(object gate)
  36. {
  37. this.gate = gate;
  38. subscription.Disposable = source.Materialize().SubscribeSafe(this);
  39. }
  40. public void Dequeue()
  41. {
  42. Queue.Dequeue();
  43. }
  44. protected override void OnNextCore(Notification<T> notification)
  45. {
  46. lock (gate)
  47. {
  48. if (!isDisposed)
  49. {
  50. if (notification.Kind == NotificationKind.OnError)
  51. {
  52. onError(notification.Exception);
  53. return;
  54. }
  55. Queue.Enqueue(notification);
  56. foreach (var activePlan in activePlans.ToArray())
  57. activePlan.Match();
  58. }
  59. }
  60. }
  61. protected override void OnErrorCore(Exception exception)
  62. {
  63. }
  64. protected override void OnCompletedCore()
  65. {
  66. }
  67. internal void RemoveActivePlan(ActivePlan activePlan)
  68. {
  69. activePlans.Remove(activePlan);
  70. if (activePlans.Count == 0)
  71. Dispose();
  72. }
  73. protected override void Dispose(bool disposing)
  74. {
  75. base.Dispose(disposing);
  76. if (!isDisposed)
  77. {
  78. if (disposing)
  79. subscription.Dispose();
  80. isDisposed = true;
  81. }
  82. }
  83. }
  84. }