RunAsync.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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.Reactive.Subjects;
  6. using System.Threading;
  7. namespace System.Reactive.Linq
  8. {
  9. // REVIEW: Consider using these for GetAwaiter.
  10. partial class AsyncObservable
  11. {
  12. public static AsyncAsyncSubject<TSource> RunAsync<TSource>(this IAsyncObservable<TSource> source, CancellationToken token)
  13. {
  14. if (source == null)
  15. throw new ArgumentNullException(nameof(source));
  16. var subject = new SequentialAsyncAsyncSubject<TSource>();
  17. if (token.IsCancellationRequested)
  18. {
  19. var ignored = subject.OnErrorAsync(new OperationCanceledException(token));
  20. return subject;
  21. }
  22. var subscribeTask = source.SubscribeSafeAsync(subject);
  23. subscribeTask.ContinueWith(t =>
  24. {
  25. if (t.Exception != null)
  26. {
  27. subject.OnErrorAsync(t.Exception); // NB: Should not occur due to use of SubscribeSafeAsync.
  28. }
  29. });
  30. if (token.CanBeCanceled)
  31. {
  32. var d = new SingleAssignmentAsyncDisposable();
  33. subscribeTask.ContinueWith(t =>
  34. {
  35. if (t.Exception == null)
  36. {
  37. var ignored = d.AssignAsync(t.Result);
  38. }
  39. });
  40. token.Register(() =>
  41. {
  42. var ignored = d.DisposeAsync();
  43. });
  44. }
  45. return subject;
  46. }
  47. public static AsyncAsyncSubject<TSource> RunAsync<TSource>(this IConnectableAsyncObservable<TSource> source, CancellationToken token)
  48. {
  49. if (source == null)
  50. throw new ArgumentNullException(nameof(source));
  51. var subject = new SequentialAsyncAsyncSubject<TSource>();
  52. if (token.IsCancellationRequested)
  53. {
  54. var ignored = subject.OnErrorAsync(new OperationCanceledException(token));
  55. return subject;
  56. }
  57. var d = new CompositeAsyncDisposable();
  58. var subscribeTask = source.SubscribeSafeAsync(subject);
  59. subscribeTask.ContinueWith(t =>
  60. {
  61. if (t.Exception != null)
  62. {
  63. subject.OnErrorAsync(t.Exception); // NB: Should not occur due to use of SubscribeSafeAsync.
  64. }
  65. else
  66. {
  67. var ignored = d.AddAsync(t.Result);
  68. source.ConnectAsync().ContinueWith(t2 =>
  69. {
  70. if (t2.Exception == null)
  71. {
  72. var ignored2 = d.AddAsync(t2.Result);
  73. }
  74. });
  75. }
  76. });
  77. if (token.CanBeCanceled)
  78. {
  79. token.Register(() =>
  80. {
  81. var ignored = d.DisposeAsync();
  82. });
  83. }
  84. return subject;
  85. }
  86. }
  87. }