BehaviorSubject.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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> : SubjectBase<T>, IDisposable
  11. {
  12. #region Fields
  13. private readonly object _gate = new object();
  14. private ImmutableList<IObserver<T>> _observers;
  15. private bool _isStopped;
  16. private T _value;
  17. private Exception _exception;
  18. private bool _isDisposed;
  19. #endregion
  20. #region Constructors
  21. /// <summary>
  22. /// 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.
  23. /// </summary>
  24. /// <param name="value">Initial value sent to observers when no other value has been received by the subject yet.</param>
  25. public BehaviorSubject(T value)
  26. {
  27. _value = value;
  28. _observers = ImmutableList<IObserver<T>>.Empty;
  29. }
  30. #endregion
  31. #region Properties
  32. /// <summary>
  33. /// Indicates whether the subject has observers subscribed to it.
  34. /// </summary>
  35. public override bool HasObservers
  36. {
  37. get
  38. {
  39. var observers = _observers;
  40. return observers != null && observers.Data.Length > 0;
  41. }
  42. }
  43. /// <summary>
  44. /// Indicates whether the subject has been disposed.
  45. /// </summary>
  46. public override bool IsDisposed
  47. {
  48. get
  49. {
  50. lock (_gate)
  51. {
  52. return _isDisposed;
  53. }
  54. }
  55. }
  56. /// <summary>
  57. /// Gets the current value or throws an exception.
  58. /// </summary>
  59. /// <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>
  60. /// <remarks>
  61. /// <para><see cref="Value"/> is frozen after <see cref="OnCompleted"/> is called.</para>
  62. /// <para>After <see cref="OnError"/> is called, <see cref="Value"/> always throws the specified exception.</para>
  63. /// <para>An exception is always thrown after <see cref="Dispose"/> is called.</para>
  64. /// <alert type="caller">
  65. /// 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.
  66. /// In some cases, it may be necessary for a caller to use external synchronization to avoid race conditions.
  67. /// </alert>
  68. /// </remarks>
  69. /// <exception cref="ObjectDisposedException">Dispose was called.</exception>
  70. public T Value
  71. {
  72. get
  73. {
  74. lock (_gate)
  75. {
  76. CheckDisposed();
  77. if (_exception != null)
  78. {
  79. throw _exception;
  80. }
  81. return _value;
  82. }
  83. }
  84. }
  85. #endregion
  86. #region Methods
  87. /// <summary>
  88. /// Tries to get the current value or throws an exception.
  89. /// </summary>
  90. /// <param name="value">The initial value passed to the constructor until <see cref="OnNext"/> is called; after which, the last value passed to <see cref="OnNext"/>.</param>
  91. /// <returns>true if a value is available; false if the subject was disposed.</returns>
  92. /// <remarks>
  93. /// <para>The value returned from <see cref="TryGetValue"/> is frozen after <see cref="OnCompleted"/> is called.</para>
  94. /// <para>After <see cref="OnError"/> is called, <see cref="TryGetValue"/> always throws the specified exception.</para>
  95. /// <alert type="caller">
  96. /// Calling <see cref="TryGetValue"/> is a thread-safe operation, though there's a potential race condition when <see cref="OnNext"/> or <see cref="OnError"/> are being invoked concurrently.
  97. /// In some cases, it may be necessary for a caller to use external synchronization to avoid race conditions.
  98. /// </alert>
  99. /// </remarks>
  100. public bool TryGetValue(out T value)
  101. {
  102. lock (_gate)
  103. {
  104. if (_isDisposed)
  105. {
  106. value = default(T);
  107. return false;
  108. }
  109. else if (_exception != null)
  110. {
  111. throw _exception;
  112. }
  113. else
  114. {
  115. value = _value;
  116. return true;
  117. }
  118. }
  119. }
  120. #region IObserver<T> implementation
  121. /// <summary>
  122. /// Notifies all subscribed observers about the end of the sequence.
  123. /// </summary>
  124. public override void OnCompleted()
  125. {
  126. var os = default(IObserver<T>[]);
  127. lock (_gate)
  128. {
  129. CheckDisposed();
  130. if (!_isStopped)
  131. {
  132. os = _observers.Data;
  133. _observers = ImmutableList<IObserver<T>>.Empty;
  134. _isStopped = true;
  135. }
  136. }
  137. if (os != null)
  138. {
  139. foreach (var o in os)
  140. o.OnCompleted();
  141. }
  142. }
  143. /// <summary>
  144. /// Notifies all subscribed observers about the exception.
  145. /// </summary>
  146. /// <param name="error">The exception to send to all observers.</param>
  147. /// <exception cref="ArgumentNullException"><paramref name="error"/> is null.</exception>
  148. public override void OnError(Exception error)
  149. {
  150. if (error == null)
  151. throw new ArgumentNullException("error");
  152. var os = default(IObserver<T>[]);
  153. lock (_gate)
  154. {
  155. CheckDisposed();
  156. if (!_isStopped)
  157. {
  158. os = _observers.Data;
  159. _observers = ImmutableList<IObserver<T>>.Empty;
  160. _isStopped = true;
  161. _exception = error;
  162. }
  163. }
  164. if (os != null)
  165. {
  166. foreach (var o in os)
  167. o.OnError(error);
  168. }
  169. }
  170. /// <summary>
  171. /// Notifies all subscribed observers about the arrival of the specified element in the sequence.
  172. /// </summary>
  173. /// <param name="value">The value to send to all observers.</param>
  174. public override void OnNext(T value)
  175. {
  176. var os = default(IObserver<T>[]);
  177. lock (_gate)
  178. {
  179. CheckDisposed();
  180. if (!_isStopped)
  181. {
  182. _value = value;
  183. os = _observers.Data;
  184. }
  185. }
  186. if (os != null)
  187. {
  188. foreach (var o in os)
  189. o.OnNext(value);
  190. }
  191. }
  192. #endregion
  193. #region IObservable<T> implementation
  194. /// <summary>
  195. /// Subscribes an observer to the subject.
  196. /// </summary>
  197. /// <param name="observer">Observer to subscribe to the subject.</param>
  198. /// <returns>Disposable object that can be used to unsubscribe the observer from the subject.</returns>
  199. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  200. public override IDisposable Subscribe(IObserver<T> observer)
  201. {
  202. if (observer == null)
  203. throw new ArgumentNullException("observer");
  204. var ex = default(Exception);
  205. lock (_gate)
  206. {
  207. CheckDisposed();
  208. if (!_isStopped)
  209. {
  210. _observers = _observers.Add(observer);
  211. observer.OnNext(_value);
  212. return new Subscription(this, observer);
  213. }
  214. ex = _exception;
  215. }
  216. if (ex != null)
  217. observer.OnError(ex);
  218. else
  219. observer.OnCompleted();
  220. return Disposable.Empty;
  221. }
  222. #endregion
  223. #region IDisposable implementation
  224. /// <summary>
  225. /// Unsubscribe all observers and release resources.
  226. /// </summary>
  227. public override void Dispose()
  228. {
  229. lock (_gate)
  230. {
  231. _isDisposed = true;
  232. _observers = null;
  233. _value = default(T);
  234. _exception = null;
  235. }
  236. }
  237. private void CheckDisposed()
  238. {
  239. if (_isDisposed)
  240. throw new ObjectDisposedException(string.Empty);
  241. }
  242. #endregion
  243. class Subscription : IDisposable
  244. {
  245. private readonly BehaviorSubject<T> _subject;
  246. private IObserver<T> _observer;
  247. public Subscription(BehaviorSubject<T> subject, IObserver<T> observer)
  248. {
  249. _subject = subject;
  250. _observer = observer;
  251. }
  252. public void Dispose()
  253. {
  254. if (_observer != null)
  255. {
  256. lock (_subject._gate)
  257. {
  258. if (!_subject._isDisposed && _observer != null)
  259. {
  260. _subject._observers = _subject._observers.Remove(_observer);
  261. _observer = null;
  262. }
  263. }
  264. }
  265. }
  266. }
  267. #endregion
  268. }
  269. }