AsyncSubject.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. using System.Threading;
  4. using System.Runtime.CompilerServices;
  5. using System.Reactive.Concurrency;
  6. namespace System.Reactive.Subjects
  7. {
  8. /// <summary>
  9. /// Represents the result of an asynchronous operation.
  10. /// The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
  11. /// </summary>
  12. /// <typeparam name="T">The type of the elements processed by the subject.</typeparam>
  13. public sealed class AsyncSubject<T> : SubjectBase<T>, IDisposable
  14. #if HAS_AWAIT
  15. , INotifyCompletion
  16. #endif
  17. {
  18. #region Fields
  19. private readonly object _gate = new object();
  20. private ImmutableList<IObserver<T>> _observers;
  21. private bool _isDisposed;
  22. private bool _isStopped;
  23. private T _value;
  24. private bool _hasValue;
  25. private Exception _exception;
  26. #endregion
  27. #region Constructors
  28. /// <summary>
  29. /// Creates a subject that can only receive one value and that value is cached for all future observations.
  30. /// </summary>
  31. public AsyncSubject()
  32. {
  33. _observers = ImmutableList<IObserver<T>>.Empty;
  34. }
  35. #endregion
  36. #region Properties
  37. /// <summary>
  38. /// Indicates whether the subject has observers subscribed to it.
  39. /// </summary>
  40. public override bool HasObservers
  41. {
  42. get
  43. {
  44. var observers = _observers;
  45. return observers != null && observers.Data.Length > 0;
  46. }
  47. }
  48. /// <summary>
  49. /// Indicates whether the subject has been disposed.
  50. /// </summary>
  51. public override bool IsDisposed
  52. {
  53. get
  54. {
  55. lock (_gate)
  56. {
  57. return _isDisposed;
  58. }
  59. }
  60. }
  61. #endregion
  62. #region Methods
  63. #region IObserver<T> implementation
  64. /// <summary>
  65. /// Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
  66. /// </summary>
  67. public override void OnCompleted()
  68. {
  69. var os = default(IObserver<T>[]);
  70. var v = default(T);
  71. var hv = false;
  72. lock (_gate)
  73. {
  74. CheckDisposed();
  75. if (!_isStopped)
  76. {
  77. os = _observers.Data;
  78. _observers = ImmutableList<IObserver<T>>.Empty;
  79. _isStopped = true;
  80. v = _value;
  81. hv = _hasValue;
  82. }
  83. }
  84. if (os != null)
  85. {
  86. if (hv)
  87. {
  88. foreach (var o in os)
  89. {
  90. o.OnNext(v);
  91. o.OnCompleted();
  92. }
  93. }
  94. else
  95. foreach (var o in os)
  96. o.OnCompleted();
  97. }
  98. }
  99. /// <summary>
  100. /// Notifies all subscribed observers about the exception.
  101. /// </summary>
  102. /// <param name="error">The exception to send to all observers.</param>
  103. /// <exception cref="ArgumentNullException"><paramref name="error"/> is null.</exception>
  104. public override void OnError(Exception error)
  105. {
  106. if (error == null)
  107. throw new ArgumentNullException("error");
  108. var os = default(IObserver<T>[]);
  109. lock (_gate)
  110. {
  111. CheckDisposed();
  112. if (!_isStopped)
  113. {
  114. os = _observers.Data;
  115. _observers = ImmutableList<IObserver<T>>.Empty;
  116. _isStopped = true;
  117. _exception = error;
  118. }
  119. }
  120. if (os != null)
  121. foreach (var o in os)
  122. o.OnError(error);
  123. }
  124. /// <summary>
  125. /// Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
  126. /// </summary>
  127. /// <param name="value">The value to store in the subject.</param>
  128. public override void OnNext(T value)
  129. {
  130. lock (_gate)
  131. {
  132. CheckDisposed();
  133. if (!_isStopped)
  134. {
  135. _value = value;
  136. _hasValue = true;
  137. }
  138. }
  139. }
  140. #endregion
  141. #region IObservable<T> implementation
  142. /// <summary>
  143. /// Subscribes an observer to the subject.
  144. /// </summary>
  145. /// <param name="observer">Observer to subscribe to the subject.</param>
  146. /// <returns>Disposable object that can be used to unsubscribe the observer from the subject.</returns>
  147. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  148. public override IDisposable Subscribe(IObserver<T> observer)
  149. {
  150. if (observer == null)
  151. throw new ArgumentNullException("observer");
  152. var ex = default(Exception);
  153. var v = default(T);
  154. var hv = false;
  155. lock (_gate)
  156. {
  157. CheckDisposed();
  158. if (!_isStopped)
  159. {
  160. _observers = _observers.Add(observer);
  161. return new Subscription(this, observer);
  162. }
  163. ex = _exception;
  164. hv = _hasValue;
  165. v = _value;
  166. }
  167. if (ex != null)
  168. {
  169. observer.OnError(ex);
  170. }
  171. else if (hv)
  172. {
  173. observer.OnNext(v);
  174. observer.OnCompleted();
  175. }
  176. else
  177. {
  178. observer.OnCompleted();
  179. }
  180. return Disposable.Empty;
  181. }
  182. class Subscription : IDisposable
  183. {
  184. private readonly AsyncSubject<T> _subject;
  185. private IObserver<T> _observer;
  186. public Subscription(AsyncSubject<T> subject, IObserver<T> observer)
  187. {
  188. _subject = subject;
  189. _observer = observer;
  190. }
  191. public void Dispose()
  192. {
  193. if (_observer != null)
  194. {
  195. lock (_subject._gate)
  196. {
  197. if (!_subject._isDisposed && _observer != null)
  198. {
  199. _subject._observers = _subject._observers.Remove(_observer);
  200. _observer = null;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. #endregion
  207. #region IDisposable implementation
  208. void CheckDisposed()
  209. {
  210. if (_isDisposed)
  211. throw new ObjectDisposedException(string.Empty);
  212. }
  213. /// <summary>
  214. /// Unsubscribe all observers and release resources.
  215. /// </summary>
  216. public override void Dispose()
  217. {
  218. lock (_gate)
  219. {
  220. _isDisposed = true;
  221. _observers = null;
  222. _exception = null;
  223. _value = default(T);
  224. }
  225. }
  226. #endregion
  227. #region Await support
  228. #if HAS_AWAIT
  229. /// <summary>
  230. /// Gets an awaitable object for the current AsyncSubject.
  231. /// </summary>
  232. /// <returns>Object that can be awaited.</returns>
  233. public AsyncSubject<T> GetAwaiter()
  234. {
  235. return this;
  236. }
  237. /// <summary>
  238. /// Specifies a callback action that will be invoked when the subject completes.
  239. /// </summary>
  240. /// <param name="continuation">Callback action that will be invoked when the subject completes.</param>
  241. /// <exception cref="ArgumentNullException"><paramref name="continuation"/> is null.</exception>
  242. public void OnCompleted(Action continuation)
  243. {
  244. if (continuation == null)
  245. throw new ArgumentNullException("continuation");
  246. OnCompleted(continuation, true);
  247. }
  248. #endif
  249. private void OnCompleted(Action continuation, bool originalContext)
  250. {
  251. //
  252. // [OK] Use of unsafe Subscribe: this type's Subscribe implementation is safe.
  253. //
  254. this.Subscribe/*Unsafe*/(new AwaitObserver(continuation, originalContext));
  255. }
  256. class AwaitObserver : IObserver<T>
  257. {
  258. #if HAS_AWAIT
  259. private readonly SynchronizationContext _context;
  260. #endif
  261. private readonly Action _callback;
  262. public AwaitObserver(Action callback, bool originalContext)
  263. {
  264. #if HAS_AWAIT
  265. if (originalContext)
  266. _context = SynchronizationContext.Current;
  267. #else
  268. System.Diagnostics.Debug.Assert(!originalContext);
  269. #endif
  270. _callback = callback;
  271. }
  272. public void OnCompleted()
  273. {
  274. InvokeOnOriginalContext();
  275. }
  276. public void OnError(Exception error)
  277. {
  278. InvokeOnOriginalContext();
  279. }
  280. public void OnNext(T value)
  281. {
  282. }
  283. private void InvokeOnOriginalContext()
  284. {
  285. #if HAS_AWAIT
  286. if (_context != null)
  287. {
  288. //
  289. // No need for OperationStarted and OperationCompleted calls here;
  290. // this code is invoked through await support and will have a way
  291. // to observe its start/complete behavior, either through returned
  292. // Task objects or the async method builder's interaction with the
  293. // SynchronizationContext object.
  294. //
  295. _context.Post(c => ((Action)c)(), _callback);
  296. }
  297. else
  298. #endif
  299. {
  300. _callback();
  301. }
  302. }
  303. }
  304. /// <summary>
  305. /// Gets whether the AsyncSubject has completed.
  306. /// </summary>
  307. public bool IsCompleted
  308. {
  309. get
  310. {
  311. return _isStopped;
  312. }
  313. }
  314. /// <summary>
  315. /// Gets the last element of the subject, potentially blocking until the subject completes successfully or exceptionally.
  316. /// </summary>
  317. /// <returns>The last element of the subject. Throws an InvalidOperationException if no element was received.</returns>
  318. /// <exception cref="InvalidOperationException">The source sequence is empty.</exception>
  319. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Await pattern for C# and VB compilers.")]
  320. public T GetResult()
  321. {
  322. if (!_isStopped)
  323. {
  324. var e = new ManualResetEvent(false);
  325. OnCompleted(() => e.Set(), false);
  326. e.WaitOne();
  327. }
  328. _exception.ThrowIfNotNull();
  329. if (!_hasValue)
  330. throw new InvalidOperationException(Strings_Linq.NO_ELEMENTS);
  331. return _value;
  332. }
  333. #endregion
  334. #endregion
  335. }
  336. }