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