BehaviorSubject.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 = ImmutableList<IObserver<T>>.Empty;
  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 = ImmutableList<IObserver<T>>.Empty;
  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 = ImmutableList<IObserver<T>>.Empty;
  106. _isStopped = true;
  107. _exception = error;
  108. }
  109. }
  110. if (os != null)
  111. {
  112. foreach (var o in os)
  113. o.OnError(error);
  114. }
  115. }
  116. /// <summary>
  117. /// Notifies all subscribed observers about the arrival of the specified element in the sequence.
  118. /// </summary>
  119. /// <param name="value">The value to send to all observers.</param>
  120. public void OnNext(T value)
  121. {
  122. var os = default(IObserver<T>[]);
  123. lock (_gate)
  124. {
  125. CheckDisposed();
  126. if (!_isStopped)
  127. {
  128. _value = value;
  129. os = _observers.Data;
  130. }
  131. }
  132. if (os != null)
  133. {
  134. foreach (var o in os)
  135. o.OnNext(value);
  136. }
  137. }
  138. /// <summary>
  139. /// Subscribes an observer to the subject.
  140. /// </summary>
  141. /// <param name="observer">Observer to subscribe to the subject.</param>
  142. /// <returns>Disposable object that can be used to unsubscribe the observer from the subject.</returns>
  143. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  144. public IDisposable Subscribe(IObserver<T> observer)
  145. {
  146. if (observer == null)
  147. throw new ArgumentNullException("observer");
  148. var ex = default(Exception);
  149. lock (_gate)
  150. {
  151. CheckDisposed();
  152. if (!_isStopped)
  153. {
  154. _observers = _observers.Add(observer);
  155. observer.OnNext(_value);
  156. return new Subscription(this, observer);
  157. }
  158. ex = _exception;
  159. }
  160. if (ex != null)
  161. observer.OnError(ex);
  162. else
  163. observer.OnCompleted();
  164. return Disposable.Empty;
  165. }
  166. /// <summary>
  167. /// Unsubscribe all observers and release resources.
  168. /// </summary>
  169. public void Dispose()
  170. {
  171. lock (_gate)
  172. {
  173. _isDisposed = true;
  174. _observers = null;
  175. _value = default(T);
  176. _exception = null;
  177. }
  178. }
  179. private void CheckDisposed()
  180. {
  181. if (_isDisposed)
  182. throw new ObjectDisposedException(string.Empty);
  183. }
  184. class Subscription : IDisposable
  185. {
  186. private readonly BehaviorSubject<T> _subject;
  187. private IObserver<T> _observer;
  188. public Subscription(BehaviorSubject<T> subject, IObserver<T> observer)
  189. {
  190. _subject = subject;
  191. _observer = observer;
  192. }
  193. public void Dispose()
  194. {
  195. if (_observer != null)
  196. {
  197. lock (_subject._gate)
  198. {
  199. if (!_subject._isDisposed && _observer != null)
  200. {
  201. _subject._observers = _subject._observers.Remove(_observer);
  202. _observer = null;
  203. }
  204. }
  205. }
  206. }
  207. }
  208. }
  209. }