BehaviorSubject.cs 10 KB

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