TakeUntil.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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.Threading.Tasks;
  7. namespace System.Reactive.Linq
  8. {
  9. partial class AsyncObservable
  10. {
  11. public static IAsyncObservable<TSource> TakeUntil<TSource, TUntil>(this IAsyncObservable<TSource> source, IAsyncObservable<TUntil> until)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. if (until == null)
  16. throw new ArgumentNullException(nameof(until));
  17. return Create<TSource>(async observer =>
  18. {
  19. var (sourceObserver, untilObserver) = AsyncObserver.TakeUntil<TSource, TUntil>(observer);
  20. var d1 = await source.SubscribeAsync(sourceObserver).ConfigureAwait(false);
  21. var d2 = await until.SubscribeAsync(untilObserver).ConfigureAwait(false);
  22. return StableCompositeAsyncDisposable.Create(d1, d2);
  23. });
  24. }
  25. }
  26. partial class AsyncObserver
  27. {
  28. public static (IAsyncObserver<TSource>, IAsyncObserver<TUntil>) TakeUntil<TSource, TUntil>(IAsyncObserver<TSource> observer)
  29. {
  30. if (observer == null)
  31. throw new ArgumentNullException(nameof(observer));
  32. var gate = new AsyncLock();
  33. return
  34. (
  35. Create<TSource>(
  36. async x =>
  37. {
  38. using (await gate.LockAsync().ConfigureAwait(false))
  39. {
  40. await observer.OnNextAsync(x).ConfigureAwait(false);
  41. }
  42. },
  43. async ex =>
  44. {
  45. using (await gate.LockAsync().ConfigureAwait(false))
  46. {
  47. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  48. }
  49. },
  50. async () =>
  51. {
  52. using (await gate.LockAsync().ConfigureAwait(false))
  53. {
  54. await observer.OnCompletedAsync().ConfigureAwait(false);
  55. }
  56. }
  57. ),
  58. Create<TUntil>(
  59. async y =>
  60. {
  61. using (await gate.LockAsync().ConfigureAwait(false))
  62. {
  63. await observer.OnCompletedAsync().ConfigureAwait(false);
  64. }
  65. },
  66. async ex =>
  67. {
  68. using (await gate.LockAsync().ConfigureAwait(false))
  69. {
  70. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  71. }
  72. },
  73. () => Task.CompletedTask
  74. )
  75. );
  76. }
  77. }
  78. }