AsyncSubject.cs 11 KB

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