BehaviorSubject.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System.Reactive.Disposables;
  3. namespace System.Reactive.Subjects
  4. {
  5. /// <summary>
  6. /// Represents a value that changes over time.
  7. /// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
  8. /// </summary>
  9. /// <typeparam name="T">The type of the elements processed by the subject.</typeparam>
  10. public sealed class BehaviorSubject<T> : ISubject<T>, IDisposable
  11. {
  12. private readonly object _gate = new object();
  13. private ImmutableList<IObserver<T>> _observers;
  14. private bool _isStopped;
  15. private T _value;
  16. private Exception _exception;
  17. private bool _isDisposed;
  18. /// <summary>
  19. /// Initializes a new instance of the <see cref="System.Reactive.Subjects.BehaviorSubject&lt;T&gt;"/> class which creates a subject that caches its last value and starts with the specified value.
  20. /// </summary>
  21. /// <param name="value">Initial value sent to observers when no other value has been received by the subject yet.</param>
  22. public BehaviorSubject(T value)
  23. {
  24. _value = value;
  25. _observers = new ImmutableList<IObserver<T>>();
  26. }
  27. /// <summary>
  28. /// Indicates whether the subject has observers subscribed to it.
  29. /// </summary>
  30. public bool HasObservers
  31. {
  32. get
  33. {
  34. var observers = _observers;
  35. return observers != null && observers.Data.Length > 0;
  36. }
  37. }
  38. /// <summary>
  39. /// Gets the current value or throws an exception.
  40. /// </summary>
  41. /// <value>The initial value passed to the constructor until <see cref="OnNext"/> is called; after which, the last value passed to <see cref="OnNext"/>.</value>
  42. /// <remarks>
  43. /// <para><see cref="Value"/> is frozen after <see cref="OnCompleted"/> is called.</para>
  44. /// <para>After <see cref="OnError"/> is called, <see cref="Value"/> always throws the specified exception.</para>
  45. /// <para>An exception is always thrown after <see cref="Dispose"/> is called.</para>
  46. /// <alert type="caller">
  47. /// Reading <see cref="Value"/> is a thread-safe operation, though there's a potential race condition when <see cref="OnNext"/> or <see cref="OnError"/> are being invoked concurrently.
  48. /// In some cases, it may be necessary for a caller to use external synchronization to avoid race conditions.
  49. /// </alert>
  50. /// </remarks>
  51. /// <exception cref="ObjectDisposedException">Dispose was called.</exception>
  52. public T Value
  53. {
  54. get
  55. {
  56. lock (_gate)
  57. {
  58. CheckDisposed();
  59. if (_exception != null)
  60. {
  61. throw _exception;
  62. }
  63. return _value;
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// Notifies all subscribed observers about the end of the sequence.
  69. /// </summary>
  70. public void OnCompleted()
  71. {
  72. var os = default(IObserver<T>[]);
  73. lock (_gate)
  74. {
  75. CheckDisposed();
  76. if (!_isStopped)
  77. {
  78. os = _observers.Data;
  79. _observers = new ImmutableList<IObserver<T>>();
  80. _isStopped = true;
  81. }
  82. }
  83. if (os != null)
  84. {
  85. foreach (var o in os)
  86. o.OnCompleted();
  87. }
  88. }
  89. /// <summary>
  90. /// Notifies all subscribed observers about the exception.
  91. /// </summary>
  92. /// <param name="error">The exception to send to all observers.</param>
  93. /// <exception cref="ArgumentNullException"><paramref name="error"/> is null.</exception>
  94. public void OnError(Exception error)
  95. {
  96. if (error == null)
  97. throw new ArgumentNullException("error");
  98. var os = default(IObserver<T>[]);
  99. lock (_gate)
  100. {
  101. CheckDisposed();
  102. if (!_isStopped)
  103. {
  104. os = _observers.Data;
  105. _observers = new ImmutableList<IObserver<T>>();
  106. _isStopped = true;
  107. _exception = error;
  108. }
  109. }
  110. if (os != null)
  111. foreach (var o in os)
  112. o.OnError(error);
  113. }
  114. /// <summary>
  115. /// Notifies all subscribed observers about the arrival of the specified element in the sequence.
  116. /// </summary>
  117. /// <param name="value">The value to send to all observers.</param>
  118. public void OnNext(T value)
  119. {
  120. var os = default(IObserver<T>[]);
  121. lock (_gate)
  122. {
  123. CheckDisposed();
  124. if (!_isStopped)
  125. {
  126. _value = value;
  127. os = _observers.Data;
  128. }
  129. }
  130. if (os != null)
  131. {
  132. foreach (var o in os)
  133. o.OnNext(value);
  134. }
  135. }
  136. /// <summary>
  137. /// Subscribes an observer to the subject.
  138. /// </summary>
  139. /// <param name="observer">Observer to subscribe to the subject.</param>
  140. /// <returns>Disposable object that can be used to unsubscribe the observer from the subject.</returns>
  141. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  142. public IDisposable Subscribe(IObserver<T> observer)
  143. {
  144. if (observer == null)
  145. throw new ArgumentNullException("observer");
  146. var ex = default(Exception);
  147. lock (_gate)
  148. {
  149. CheckDisposed();
  150. if (!_isStopped)
  151. {
  152. _observers = _observers.Add(observer);
  153. observer.OnNext(_value);
  154. return new Subscription(this, observer);
  155. }
  156. ex = _exception;
  157. }
  158. if (ex != null)
  159. observer.OnError(ex);
  160. else
  161. observer.OnCompleted();
  162. return Disposable.Empty;
  163. }
  164. /// <summary>
  165. /// Unsubscribe all observers and release resources.
  166. /// </summary>
  167. public void Dispose()
  168. {
  169. lock (_gate)
  170. {
  171. _isDisposed = true;
  172. _observers = null;
  173. _value = default(T);
  174. _exception = null;
  175. }
  176. }
  177. private void CheckDisposed()
  178. {
  179. if (_isDisposed)
  180. throw new ObjectDisposedException(string.Empty);
  181. }
  182. class Subscription : IDisposable
  183. {
  184. private readonly BehaviorSubject<T> _subject;
  185. private IObserver<T> _observer;
  186. public Subscription(BehaviorSubject<T> subject, IObserver<T> observer)
  187. {
  188. _subject = subject;
  189. _observer = observer;
  190. }
  191. public void Dispose()
  192. {
  193. if (_observer != null)
  194. {
  195. lock (_subject._gate)
  196. {
  197. if (!_subject._isDisposed && _observer != null)
  198. {
  199. _subject._observers = _subject._observers.Remove(_observer);
  200. _observer = null;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. }
  207. }