Observable.Extensions.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System.ComponentModel;
  3. using System.Reactive;
  4. using System.Reactive.Disposables;
  5. using System.Threading;
  6. namespace System
  7. {
  8. /// <summary>
  9. /// Provides a set of static methods for subscribing delegates to observables.
  10. /// </summary>
  11. public static class ObservableExtensions
  12. {
  13. #region Subscribe delegate-based overloads
  14. /// <summary>
  15. /// Subscribes to the observable sequence without specifying any handlers.
  16. /// This method can be used to evaluate the observable sequence for its side-effects only.
  17. /// </summary>
  18. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  19. /// <param name="source">Observable sequence to subscribe to.</param>
  20. /// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  22. public static IDisposable Subscribe<T>(this IObservable<T> source)
  23. {
  24. if (source == null)
  25. throw new ArgumentNullException("source");
  26. //
  27. // [OK] Use of unsafe Subscribe: non-pretentious constructor for an observer; this overload is not to be used internally.
  28. //
  29. return source.Subscribe/*Unsafe*/(new AnonymousObserver<T>(Stubs<T>.Ignore, Stubs.Throw, Stubs.Nop));
  30. }
  31. /// <summary>
  32. /// Subscribes an element handler to an observable sequence.
  33. /// </summary>
  34. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  35. /// <param name="source">Observable sequence to subscribe to.</param>
  36. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  37. /// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
  38. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> is null.</exception>
  39. public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext)
  40. {
  41. if (source == null)
  42. throw new ArgumentNullException("source");
  43. if (onNext == null)
  44. throw new ArgumentNullException("onNext");
  45. //
  46. // [OK] Use of unsafe Subscribe: non-pretentious constructor for an observer; this overload is not to be used internally.
  47. //
  48. return source.Subscribe/*Unsafe*/(new AnonymousObserver<T>(onNext, Stubs.Throw, Stubs.Nop));
  49. }
  50. /// <summary>
  51. /// Subscribes an element handler and an exception handler to an observable sequence.
  52. /// </summary>
  53. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  54. /// <param name="source">Observable sequence to subscribe to.</param>
  55. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  56. /// <param name="onError">Action to invoke upon exceptional termination of the observable sequence.</param>
  57. /// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
  58. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onError"/> is null.</exception>
  59. public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError)
  60. {
  61. if (source == null)
  62. throw new ArgumentNullException("source");
  63. if (onNext == null)
  64. throw new ArgumentNullException("onNext");
  65. if (onError == null)
  66. throw new ArgumentNullException("onError");
  67. //
  68. // [OK] Use of unsafe Subscribe: non-pretentious constructor for an observer; this overload is not to be used internally.
  69. //
  70. return source.Subscribe/*Unsafe*/(new AnonymousObserver<T>(onNext, onError, Stubs.Nop));
  71. }
  72. /// <summary>
  73. /// Subscribes an element handler and a completion handler to an observable sequence.
  74. /// </summary>
  75. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  76. /// <param name="source">Observable sequence to subscribe to.</param>
  77. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  78. /// <param name="onCompleted">Action to invoke upon graceful termination of the observable sequence.</param>
  79. /// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
  80. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onCompleted"/> is null.</exception>
  81. public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted)
  82. {
  83. if (source == null)
  84. throw new ArgumentNullException("source");
  85. if (onNext == null)
  86. throw new ArgumentNullException("onNext");
  87. if (onCompleted == null)
  88. throw new ArgumentNullException("onCompleted");
  89. //
  90. // [OK] Use of unsafe Subscribe: non-pretentious constructor for an observer; this overload is not to be used internally.
  91. //
  92. return source.Subscribe/*Unsafe*/(new AnonymousObserver<T>(onNext, Stubs.Throw, onCompleted));
  93. }
  94. /// <summary>
  95. /// Subscribes an element handler, an exception handler, and a completion handler to an observable sequence.
  96. /// </summary>
  97. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  98. /// <param name="source">Observable sequence to subscribe to.</param>
  99. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  100. /// <param name="onError">Action to invoke upon exceptional termination of the observable sequence.</param>
  101. /// <param name="onCompleted">Action to invoke upon graceful termination of the observable sequence.</param>
  102. /// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
  103. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onError"/> or <paramref name="onCompleted"/> is null.</exception>
  104. public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted)
  105. {
  106. if (source == null)
  107. throw new ArgumentNullException("source");
  108. if (onNext == null)
  109. throw new ArgumentNullException("onNext");
  110. if (onError == null)
  111. throw new ArgumentNullException("onError");
  112. if (onCompleted == null)
  113. throw new ArgumentNullException("onCompleted");
  114. //
  115. // [OK] Use of unsafe Subscribe: non-pretentious constructor for an observer; this overload is not to be used internally.
  116. //
  117. return source.Subscribe/*Unsafe*/(new AnonymousObserver<T>(onNext, onError, onCompleted));
  118. }
  119. #endregion
  120. #region Subscribe overloads with CancellationToken
  121. #if !NO_TPL
  122. /// <summary>
  123. /// Subscribes an observer to an observable sequence, using a CancellationToken to support unsubscription.
  124. /// </summary>
  125. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  126. /// <param name="source">Observable sequence to subscribe to.</param>
  127. /// <param name="observer">Observer to subscribe to the sequence.</param>
  128. /// <param name="token">CancellationToken that can be signaled to unsubscribe from the source sequence.</param>
  129. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="observer"/> is null.</exception>
  130. public static void Subscribe<T>(this IObservable<T> source, IObserver<T> observer, CancellationToken token)
  131. {
  132. if (source == null)
  133. throw new ArgumentNullException("source");
  134. if (observer == null)
  135. throw new ArgumentNullException("observer");
  136. source.Subscribe_(observer, token);
  137. }
  138. /// <summary>
  139. /// Subscribes to the observable sequence without specifying any handlers, using a CancellationToken to support unsubscription.
  140. /// This method can be used to evaluate the observable sequence for its side-effects only.
  141. /// </summary>
  142. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  143. /// <param name="source">Observable sequence to subscribe to.</param>
  144. /// <param name="token">CancellationToken that can be signaled to unsubscribe from the source sequence.</param>
  145. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  146. public static void Subscribe<T>(this IObservable<T> source, CancellationToken token)
  147. {
  148. if (source == null)
  149. throw new ArgumentNullException("source");
  150. source.Subscribe_(new AnonymousObserver<T>(Stubs<T>.Ignore, Stubs.Throw, Stubs.Nop), token);
  151. }
  152. /// <summary>
  153. /// Subscribes an element handler to an observable sequence, using a CancellationToken to support unsubscription.
  154. /// </summary>
  155. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  156. /// <param name="source">Observable sequence to subscribe to.</param>
  157. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  158. /// <param name="token">CancellationToken that can be signaled to unsubscribe from the source sequence.</param>
  159. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> is null.</exception>
  160. public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, CancellationToken token)
  161. {
  162. if (source == null)
  163. throw new ArgumentNullException("source");
  164. if (onNext == null)
  165. throw new ArgumentNullException("onNext");
  166. source.Subscribe_(new AnonymousObserver<T>(onNext, Stubs.Throw, Stubs.Nop), token);
  167. }
  168. /// <summary>
  169. /// Subscribes an element handler and an exception handler to an observable sequence, using a CancellationToken to support unsubscription.
  170. /// </summary>
  171. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  172. /// <param name="source">Observable sequence to subscribe to.</param>
  173. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  174. /// <param name="onError">Action to invoke upon exceptional termination of the observable sequence.</param>
  175. /// <param name="token">CancellationToken that can be signaled to unsubscribe from the source sequence.</param>
  176. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onError"/> is null.</exception>
  177. public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, CancellationToken token)
  178. {
  179. if (source == null)
  180. throw new ArgumentNullException("source");
  181. if (onNext == null)
  182. throw new ArgumentNullException("onNext");
  183. if (onError == null)
  184. throw new ArgumentNullException("onError");
  185. source.Subscribe_(new AnonymousObserver<T>(onNext, onError, Stubs.Nop), token);
  186. }
  187. /// <summary>
  188. /// Subscribes an element handler and a completion handler to an observable sequence, using a CancellationToken to support unsubscription.
  189. /// </summary>
  190. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  191. /// <param name="source">Observable sequence to subscribe to.</param>
  192. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  193. /// <param name="onCompleted">Action to invoke upon graceful termination of the observable sequence.</param>
  194. /// <param name="token">CancellationToken that can be signaled to unsubscribe from the source sequence.</param>
  195. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onCompleted"/> is null.</exception>
  196. public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted, CancellationToken token)
  197. {
  198. if (source == null)
  199. throw new ArgumentNullException("source");
  200. if (onNext == null)
  201. throw new ArgumentNullException("onNext");
  202. if (onCompleted == null)
  203. throw new ArgumentNullException("onCompleted");
  204. source.Subscribe_(new AnonymousObserver<T>(onNext, Stubs.Throw, onCompleted), token);
  205. }
  206. /// <summary>
  207. /// Subscribes an element handler, an exception handler, and a completion handler to an observable sequence, using a CancellationToken to support unsubscription.
  208. /// </summary>
  209. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  210. /// <param name="source">Observable sequence to subscribe to.</param>
  211. /// <param name="onNext">Action to invoke for each element in the observable sequence.</param>
  212. /// <param name="onError">Action to invoke upon exceptional termination of the observable sequence.</param>
  213. /// <param name="onCompleted">Action to invoke upon graceful termination of the observable sequence.</param>
  214. /// <param name="token">CancellationToken that can be signaled to unsubscribe from the source sequence.</param>
  215. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="onNext"/> or <paramref name="onError"/> or <paramref name="onCompleted"/> is null.</exception>
  216. public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted, CancellationToken token)
  217. {
  218. if (source == null)
  219. throw new ArgumentNullException("source");
  220. if (onNext == null)
  221. throw new ArgumentNullException("onNext");
  222. if (onError == null)
  223. throw new ArgumentNullException("onError");
  224. if (onCompleted == null)
  225. throw new ArgumentNullException("onCompleted");
  226. source.Subscribe_(new AnonymousObserver<T>(onNext, onError, onCompleted), token);
  227. }
  228. private static void Subscribe_<T>(this IObservable<T> source, IObserver<T> observer, CancellationToken token)
  229. {
  230. if (token.CanBeCanceled)
  231. {
  232. if (!token.IsCancellationRequested)
  233. {
  234. var r = new SingleAssignmentDisposable();
  235. //
  236. // [OK] Use of unsafe Subscribe: exception during Subscribe doesn't orphan CancellationTokenRegistration.
  237. //
  238. var d = source.Subscribe/*Unsafe*/(
  239. observer.OnNext,
  240. ex =>
  241. {
  242. using (r)
  243. observer.OnError(ex);
  244. },
  245. () =>
  246. {
  247. using (r)
  248. observer.OnCompleted();
  249. }
  250. );
  251. r.Disposable = token.Register(d.Dispose);
  252. }
  253. }
  254. else
  255. {
  256. source.Subscribe(observer);
  257. }
  258. }
  259. #endif
  260. #endregion
  261. #region SubscribeSafe
  262. /// <summary>
  263. /// Subscribes to the specified source, re-routing synchronous exceptions during invocation of the Subscribe method to the observer's OnError channel.
  264. /// This method is typically used when writing query operators.
  265. /// </summary>
  266. /// <typeparam name="T">The type of the elements in the source sequence.</typeparam>
  267. /// <param name="source">Observable sequence to subscribe to.</param>
  268. /// <param name="observer">Observer that will be passed to the observable sequence, and that will be used for exception propagation.</param>
  269. /// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
  270. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="observer"/> is null.</exception>
  271. [EditorBrowsable(EditorBrowsableState.Advanced)]
  272. public static IDisposable SubscribeSafe<T>(this IObservable<T> source, IObserver<T> observer)
  273. {
  274. if (source == null)
  275. throw new ArgumentNullException("source");
  276. if (observer == null)
  277. throw new ArgumentNullException("observer");
  278. //
  279. // The following types are white-listed and should not exhibit exceptional behavior
  280. // for regular operation circumstances.
  281. //
  282. if (source is ObservableBase<T>)
  283. return source.Subscribe(observer);
  284. #if !NO_PERF
  285. var producer = source as IProducer<T>;
  286. if (producer != null)
  287. return producer.SubscribeRaw(observer, false);
  288. #endif
  289. var d = Disposable.Empty;
  290. try
  291. {
  292. d = source.Subscribe(observer);
  293. }
  294. catch (Exception exception)
  295. {
  296. //
  297. // The effect of redirecting the exception to the OnError channel is automatic
  298. // clean-up of query operator state for a large number of cases. For example,
  299. // consider a binary and temporal query operator with the following Subscribe
  300. // behavior (implemented using the Producer pattern with a Run method):
  301. //
  302. // public IDisposable Run(...)
  303. // {
  304. // var tm = _scheduler.Schedule(_due, Tick);
  305. //
  306. // var df = _fst.SubscribeSafe(new FstObserver(this, ...));
  307. // var ds = _snd.SubscribeSafe(new SndObserver(this, ...)); // <-- fails
  308. //
  309. // return new CompositeDisposable(tm, df, ds);
  310. // }
  311. //
  312. // If the second subscription fails, we're not leaving the first subscription
  313. // or the scheduled job hanging around. Instead, the OnError propagation to
  314. // the SndObserver should take care of a Dispose call to the observer's parent
  315. // object. The handshake between Producer and Sink objects will ultimately
  316. // cause disposal of the CompositeDisposable that's returned from the method.
  317. //
  318. observer.OnError(exception);
  319. }
  320. return d;
  321. }
  322. #endregion
  323. }
  324. }