AsyncSubject.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. namespace System.Reactive.Subjects
  8. {
  9. /// <summary>
  10. /// Represents the result of an asynchronous operation.
  11. /// The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
  12. /// </summary>
  13. /// <typeparam name="T">The type of the elements processed by the subject.</typeparam>
  14. public sealed class AsyncSubject<T> : SubjectBase<T>, IDisposable, INotifyCompletion
  15. {
  16. #region Fields
  17. private readonly object _gate = new object();
  18. private ImmutableList<IObserver<T>> _observers;
  19. private bool _isDisposed;
  20. private bool _isStopped;
  21. private T _value;
  22. private bool _hasValue;
  23. private Exception _exception;
  24. #endregion
  25. #region Constructors
  26. /// <summary>
  27. /// Creates a subject that can only receive one value and that value is cached for all future observations.
  28. /// </summary>
  29. public AsyncSubject()
  30. {
  31. _observers = ImmutableList<IObserver<T>>.Empty;
  32. }
  33. #endregion
  34. #region Properties
  35. /// <summary>
  36. /// Indicates whether the subject has observers subscribed to it.
  37. /// </summary>
  38. public override bool HasObservers => _observers?.Data.Length > 0;
  39. /// <summary>
  40. /// Indicates whether the subject has been disposed.
  41. /// </summary>
  42. public override bool IsDisposed
  43. {
  44. get
  45. {
  46. lock (_gate)
  47. {
  48. return _isDisposed;
  49. }
  50. }
  51. }
  52. #endregion
  53. #region Methods
  54. #region IObserver<T> implementation
  55. /// <summary>
  56. /// Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
  57. /// </summary>
  58. public override void OnCompleted()
  59. {
  60. var os = default(IObserver<T>[]);
  61. var v = default(T);
  62. var hv = false;
  63. lock (_gate)
  64. {
  65. CheckDisposed();
  66. if (!_isStopped)
  67. {
  68. os = _observers.Data;
  69. _observers = ImmutableList<IObserver<T>>.Empty;
  70. _isStopped = true;
  71. v = _value;
  72. hv = _hasValue;
  73. }
  74. }
  75. if (os != null)
  76. {
  77. if (hv)
  78. {
  79. foreach (var o in os)
  80. {
  81. o.OnNext(v);
  82. o.OnCompleted();
  83. }
  84. }
  85. else
  86. {
  87. foreach (var o in os)
  88. {
  89. o.OnCompleted();
  90. }
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// Notifies all subscribed observers about the exception.
  96. /// </summary>
  97. /// <param name="error">The exception to send to all observers.</param>
  98. /// <exception cref="ArgumentNullException"><paramref name="error"/> is <c>null</c>.</exception>
  99. public override void OnError(Exception error)
  100. {
  101. if (error == null)
  102. throw new ArgumentNullException(nameof(error));
  103. var os = default(IObserver<T>[]);
  104. lock (_gate)
  105. {
  106. CheckDisposed();
  107. if (!_isStopped)
  108. {
  109. os = _observers.Data;
  110. _observers = ImmutableList<IObserver<T>>.Empty;
  111. _isStopped = true;
  112. _exception = error;
  113. }
  114. }
  115. if (os != null)
  116. {
  117. foreach (var o in os)
  118. {
  119. o.OnError(error);
  120. }
  121. }
  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 <c>null</c>.</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. private sealed 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() => this;
  232. /// <summary>
  233. /// Specifies a callback action that will be invoked when the subject completes.
  234. /// </summary>
  235. /// <param name="continuation">Callback action that will be invoked when the subject completes.</param>
  236. /// <exception cref="ArgumentNullException"><paramref name="continuation"/> is <c>null</c>.</exception>
  237. public void OnCompleted(Action continuation)
  238. {
  239. if (continuation == null)
  240. throw new ArgumentNullException(nameof(continuation));
  241. OnCompleted(continuation, originalContext: true);
  242. }
  243. private void OnCompleted(Action continuation, bool originalContext)
  244. {
  245. //
  246. // [OK] Use of unsafe Subscribe: this type's Subscribe implementation is safe.
  247. //
  248. Subscribe/*Unsafe*/(new AwaitObserver(continuation, originalContext));
  249. }
  250. private sealed class AwaitObserver : IObserver<T>
  251. {
  252. private readonly SynchronizationContext _context;
  253. private readonly Action _callback;
  254. public AwaitObserver(Action callback, bool originalContext)
  255. {
  256. if (originalContext)
  257. _context = SynchronizationContext.Current;
  258. _callback = callback;
  259. }
  260. public void OnCompleted() => InvokeOnOriginalContext();
  261. public void OnError(Exception error) => InvokeOnOriginalContext();
  262. public void OnNext(T value) { }
  263. private void InvokeOnOriginalContext()
  264. {
  265. if (_context != null)
  266. {
  267. //
  268. // No need for OperationStarted and OperationCompleted calls here;
  269. // this code is invoked through await support and will have a way
  270. // to observe its start/complete behavior, either through returned
  271. // Task objects or the async method builder's interaction with the
  272. // SynchronizationContext object.
  273. //
  274. _context.Post(c => ((Action)c)(), _callback);
  275. }
  276. else
  277. {
  278. _callback();
  279. }
  280. }
  281. }
  282. /// <summary>
  283. /// Gets whether the AsyncSubject has completed.
  284. /// </summary>
  285. public bool IsCompleted => _isStopped;
  286. /// <summary>
  287. /// Gets the last element of the subject, potentially blocking until the subject completes successfully or exceptionally.
  288. /// </summary>
  289. /// <returns>The last element of the subject. Throws an InvalidOperationException if no element was received.</returns>
  290. /// <exception cref="InvalidOperationException">The source sequence is empty.</exception>
  291. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Await pattern for C# and VB compilers.")]
  292. public T GetResult()
  293. {
  294. if (!_isStopped)
  295. {
  296. var e = new ManualResetEvent(initialState: false);
  297. OnCompleted(() => e.Set(), originalContext: false);
  298. e.WaitOne();
  299. }
  300. _exception.ThrowIfNotNull();
  301. if (!_hasValue)
  302. throw new InvalidOperationException(Strings_Linq.NO_ELEMENTS);
  303. return _value;
  304. }
  305. #endregion
  306. #endregion
  307. }
  308. }