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. /// <summary>
  13. /// Gets the current value or throws an exception.
  14. /// </summary>
  15. /// <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>
  16. /// <remarks>
  17. /// <para><see cref="Value"/> is frozen after <see cref="OnCompleted"/> is called.</para>
  18. /// <para>After <see cref="OnError"/> is called, <see cref="Value"/> always throws the specified exception.</para>
  19. /// <para>An exception is always thrown after <see cref="Dispose"/> is called.</para>
  20. /// <alert type="caller">
  21. /// 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.
  22. /// In some cases, it may be necessary for a caller to use external synchronization to avoid race conditions.
  23. /// </alert>
  24. /// </remarks>
  25. /// <exception cref="ObjectDisposedException">Dispose was called.</exception>
  26. public T Value
  27. {
  28. get
  29. {
  30. lock (_gate)
  31. {
  32. CheckDisposed();
  33. if (_exception != null)
  34. {
  35. throw _exception;
  36. }
  37. return _value;
  38. }
  39. }
  40. }
  41. private readonly object _gate = new object();
  42. private ImmutableList<IObserver<T>> _observers;
  43. private bool _isStopped;
  44. private T _value;
  45. private Exception _exception;
  46. private bool _isDisposed;
  47. /// <summary>
  48. /// 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.
  49. /// </summary>
  50. /// <param name="value">Initial value sent to observers when no other value has been received by the subject yet.</param>
  51. public BehaviorSubject(T value)
  52. {
  53. _value = value;
  54. _observers = new ImmutableList<IObserver<T>>();
  55. }
  56. /// <summary>
  57. /// Indicates whether the subject has observers subscribed to it.
  58. /// </summary>
  59. public bool HasObservers
  60. {
  61. get
  62. {
  63. var observers = _observers;
  64. return observers != null && observers.Data.Length > 0;
  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. class Subscription : IDisposable
  165. {
  166. private readonly BehaviorSubject<T> _subject;
  167. private IObserver<T> _observer;
  168. public Subscription(BehaviorSubject<T> subject, IObserver<T> observer)
  169. {
  170. _subject = subject;
  171. _observer = observer;
  172. }
  173. public void Dispose()
  174. {
  175. if (_observer != null)
  176. {
  177. lock (_subject._gate)
  178. {
  179. if (!_subject._isDisposed && _observer != null)
  180. {
  181. _subject._observers = _subject._observers.Remove(_observer);
  182. _observer = null;
  183. }
  184. }
  185. }
  186. }
  187. }
  188. void CheckDisposed()
  189. {
  190. if (_isDisposed)
  191. throw new ObjectDisposedException(string.Empty);
  192. }
  193. /// <summary>
  194. /// Unsubscribe all observers and release resources.
  195. /// </summary>
  196. public void Dispose()
  197. {
  198. lock (_gate)
  199. {
  200. _isDisposed = true;
  201. _observers = null;
  202. _value = default(T);
  203. _exception = null;
  204. }
  205. }
  206. }
  207. }