Subject.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System.Reactive.Disposables;
  4. using System.Threading;
  5. namespace System.Reactive.Subjects
  6. {
  7. /// <summary>
  8. /// Represents an object that is both an observable sequence as well as an observer.
  9. /// Each notification is broadcasted to all subscribed observers.
  10. /// </summary>
  11. /// <typeparam name="T">The type of the elements processed by the subject.</typeparam>
  12. public sealed class Subject<T> : SubjectBase<T>, IDisposable
  13. {
  14. #region Fields
  15. private volatile IObserver<T> _observer;
  16. #endregion
  17. #region Constructors
  18. /// <summary>
  19. /// Creates a subject.
  20. /// </summary>
  21. public Subject()
  22. {
  23. _observer = NopObserver<T>.Instance;
  24. }
  25. #endregion
  26. #region Properties
  27. /// <summary>
  28. /// Indicates whether the subject has observers subscribed to it.
  29. /// </summary>
  30. public override bool HasObservers
  31. {
  32. get
  33. {
  34. return _observer != NopObserver<T>.Instance && !(_observer is DoneObserver<T>) && _observer != DisposedObserver<T>.Instance;
  35. }
  36. }
  37. /// <summary>
  38. /// Indicates whether the subject has been disposed.
  39. /// </summary>
  40. public override bool IsDisposed
  41. {
  42. get
  43. {
  44. return _observer is DisposedObserver<T>;
  45. }
  46. }
  47. #endregion
  48. #region Methods
  49. #region IObserver<T> implementation
  50. /// <summary>
  51. /// Notifies all subscribed observers about the end of the sequence.
  52. /// </summary>
  53. public override void OnCompleted()
  54. {
  55. var oldObserver = default(IObserver<T>);
  56. var newObserver = DoneObserver<T>.Completed;
  57. do
  58. {
  59. oldObserver = _observer;
  60. if (oldObserver == DisposedObserver<T>.Instance || oldObserver is DoneObserver<T>)
  61. break;
  62. #pragma warning disable 0420
  63. } while (Interlocked.CompareExchange(ref _observer, newObserver, oldObserver) != oldObserver);
  64. #pragma warning restore 0420
  65. oldObserver.OnCompleted();
  66. }
  67. /// <summary>
  68. /// Notifies all subscribed observers about the specified exception.
  69. /// </summary>
  70. /// <param name="error">The exception to send to all currently subscribed observers.</param>
  71. /// <exception cref="ArgumentNullException"><paramref name="error"/> is null.</exception>
  72. public override void OnError(Exception error)
  73. {
  74. if (error == null)
  75. throw new ArgumentNullException("error");
  76. var oldObserver = default(IObserver<T>);
  77. var newObserver = new DoneObserver<T> { Exception = error };
  78. do
  79. {
  80. oldObserver = _observer;
  81. if (oldObserver == DisposedObserver<T>.Instance || oldObserver is DoneObserver<T>)
  82. break;
  83. #pragma warning disable 0420
  84. } while (Interlocked.CompareExchange(ref _observer, newObserver, oldObserver) != oldObserver);
  85. #pragma warning restore 0420
  86. oldObserver.OnError(error);
  87. }
  88. /// <summary>
  89. /// Notifies all subscribed observers about the arrival of the specified element in the sequence.
  90. /// </summary>
  91. /// <param name="value">The value to send to all currently subscribed observers.</param>
  92. public override void OnNext(T value)
  93. {
  94. _observer.OnNext(value);
  95. }
  96. #endregion
  97. #region IObservable<T> implementation
  98. /// <summary>
  99. /// Subscribes an observer to the subject.
  100. /// </summary>
  101. /// <param name="observer">Observer to subscribe to the subject.</param>
  102. /// <returns>Disposable object that can be used to unsubscribe the observer from the subject.</returns>
  103. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  104. public override IDisposable Subscribe(IObserver<T> observer)
  105. {
  106. if (observer == null)
  107. throw new ArgumentNullException("observer");
  108. var oldObserver = default(IObserver<T>);
  109. var newObserver = default(IObserver<T>);
  110. do
  111. {
  112. oldObserver = _observer;
  113. if (oldObserver == DisposedObserver<T>.Instance)
  114. {
  115. throw new ObjectDisposedException("");
  116. }
  117. if (oldObserver == DoneObserver<T>.Completed)
  118. {
  119. observer.OnCompleted();
  120. return Disposable.Empty;
  121. }
  122. var done = oldObserver as DoneObserver<T>;
  123. if (done != null)
  124. {
  125. observer.OnError(done.Exception);
  126. return Disposable.Empty;
  127. }
  128. if (oldObserver == NopObserver<T>.Instance)
  129. {
  130. newObserver = observer;
  131. }
  132. else
  133. {
  134. var obs = oldObserver as Observer<T>;
  135. if (obs != null)
  136. {
  137. newObserver = obs.Add(observer);
  138. }
  139. else
  140. {
  141. newObserver = new Observer<T>(new ImmutableList<IObserver<T>>(new[] { oldObserver, observer }));
  142. }
  143. }
  144. #pragma warning disable 0420
  145. } while (Interlocked.CompareExchange(ref _observer, newObserver, oldObserver) != oldObserver);
  146. #pragma warning restore 0420
  147. return new Subscription(this, observer);
  148. }
  149. class Subscription : IDisposable
  150. {
  151. private Subject<T> _subject;
  152. private IObserver<T> _observer;
  153. public Subscription(Subject<T> subject, IObserver<T> observer)
  154. {
  155. _subject = subject;
  156. _observer = observer;
  157. }
  158. public void Dispose()
  159. {
  160. var observer = Interlocked.Exchange(ref _observer, null);
  161. if (observer == null)
  162. return;
  163. _subject.Unsubscribe(observer);
  164. _subject = null;
  165. }
  166. }
  167. private void Unsubscribe(IObserver<T> observer)
  168. {
  169. var oldObserver = default(IObserver<T>);
  170. var newObserver = default(IObserver<T>);
  171. do
  172. {
  173. oldObserver = _observer;
  174. if (oldObserver == DisposedObserver<T>.Instance || oldObserver is DoneObserver<T>)
  175. return;
  176. var obs = oldObserver as Observer<T>;
  177. if (obs != null)
  178. {
  179. newObserver = obs.Remove(observer);
  180. }
  181. else
  182. {
  183. if (oldObserver != observer)
  184. return;
  185. newObserver = NopObserver<T>.Instance;
  186. }
  187. #pragma warning disable 0420
  188. } while (Interlocked.CompareExchange(ref _observer, newObserver, oldObserver) != oldObserver);
  189. #pragma warning restore 0420
  190. }
  191. #endregion
  192. #region IDisposable implementation
  193. /// <summary>
  194. /// Releases all resources used by the current instance of the <see cref="System.Reactive.Subjects.Subject&lt;T&gt;"/> class and unsubscribes all observers.
  195. /// </summary>
  196. public override void Dispose()
  197. {
  198. _observer = DisposedObserver<T>.Instance;
  199. }
  200. #endregion
  201. #endregion
  202. }
  203. }
  204. #else
  205. using System.Reactive.Disposables;
  206. using System.Threading;
  207. namespace System.Reactive.Subjects
  208. {
  209. /// <summary>
  210. /// Represents an object that is both an observable sequence as well as an observer.
  211. /// Each notification is broadcasted to all subscribed observers.
  212. /// </summary>
  213. /// <typeparam name="T">The type of the elements processed by the subject.</typeparam>
  214. public sealed class Subject<T> : ISubject<T>, IDisposable
  215. {
  216. bool isDisposed;
  217. bool isStopped;
  218. ImmutableList<IObserver<T>> observers;
  219. object gate = new object();
  220. Exception exception;
  221. /// <summary>
  222. /// Creates a subject.
  223. /// </summary>
  224. public Subject()
  225. {
  226. observers = new ImmutableList<IObserver<T>>();
  227. }
  228. /// <summary>
  229. /// Notifies all subscribed observers about the end of the sequence.
  230. /// </summary>
  231. public void OnCompleted()
  232. {
  233. var os = default(IObserver<T>[]);
  234. lock (gate)
  235. {
  236. CheckDisposed();
  237. if (!isStopped)
  238. {
  239. os = observers.Data;
  240. observers = new ImmutableList<IObserver<T>>();
  241. isStopped = true;
  242. }
  243. }
  244. if (os != null)
  245. foreach (var o in os)
  246. o.OnCompleted();
  247. }
  248. /// <summary>
  249. /// Notifies all subscribed observers with the exception.
  250. /// </summary>
  251. /// <param name="error">The exception to send to all subscribed observers.</param>
  252. /// <exception cref="ArgumentNullException"><paramref name="error"/> is null.</exception>
  253. public void OnError(Exception error)
  254. {
  255. if (error == null)
  256. throw new ArgumentNullException("error");
  257. var os = default(IObserver<T>[]);
  258. lock (gate)
  259. {
  260. CheckDisposed();
  261. if (!isStopped)
  262. {
  263. os = observers.Data;
  264. observers = new ImmutableList<IObserver<T>>();
  265. isStopped = true;
  266. exception = error;
  267. }
  268. }
  269. if (os != null)
  270. foreach (var o in os)
  271. o.OnError(error);
  272. }
  273. /// <summary>
  274. /// Notifies all subscribed observers with the value.
  275. /// </summary>
  276. /// <param name="value">The value to send to all subscribed observers.</param>
  277. public void OnNext(T value)
  278. {
  279. var os = default(IObserver<T>[]);
  280. lock (gate)
  281. {
  282. CheckDisposed();
  283. if (!isStopped)
  284. {
  285. os = observers.Data;
  286. }
  287. }
  288. if (os != null)
  289. foreach (var o in os)
  290. o.OnNext(value);
  291. }
  292. /// <summary>
  293. /// Subscribes an observer to the subject.
  294. /// </summary>
  295. /// <param name="observer">Observer to subscribe to the subject.</param>
  296. /// <remarks>IDisposable object that can be used to unsubscribe the observer from the subject.</remarks>
  297. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  298. public IDisposable Subscribe(IObserver<T> observer)
  299. {
  300. if (observer == null)
  301. throw new ArgumentNullException("observer");
  302. lock (gate)
  303. {
  304. CheckDisposed();
  305. if (!isStopped)
  306. {
  307. observers = observers.Add(observer);
  308. return new Subscription(this, observer);
  309. }
  310. else if (exception != null)
  311. {
  312. observer.OnError(exception);
  313. return Disposable.Empty;
  314. }
  315. else
  316. {
  317. observer.OnCompleted();
  318. return Disposable.Empty;
  319. }
  320. }
  321. }
  322. void Unsubscribe(IObserver<T> observer)
  323. {
  324. lock (gate)
  325. {
  326. if (observers != null)
  327. observers = observers.Remove(observer);
  328. }
  329. }
  330. class Subscription : IDisposable
  331. {
  332. Subject<T> subject;
  333. IObserver<T> observer;
  334. public Subscription(Subject<T> subject, IObserver<T> observer)
  335. {
  336. this.subject = subject;
  337. this.observer = observer;
  338. }
  339. public void Dispose()
  340. {
  341. var o = Interlocked.Exchange<IObserver<T>>(ref observer, null);
  342. if (o != null)
  343. {
  344. subject.Unsubscribe(o);
  345. subject = null;
  346. }
  347. }
  348. }
  349. void CheckDisposed()
  350. {
  351. if (isDisposed)
  352. throw new ObjectDisposedException(string.Empty);
  353. }
  354. /// <summary>
  355. /// Unsubscribe all observers and release resources.
  356. /// </summary>
  357. public void Dispose()
  358. {
  359. lock (gate)
  360. {
  361. isDisposed = true;
  362. observers = null;
  363. }
  364. }
  365. }
  366. }
  367. #endif