AsyncSubject.cs 11 KB

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