Amb.cs 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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.Collections.Generic;
  5. using System.Reactive.Disposables;
  6. using System.Threading;
  7. namespace System.Reactive.Linq
  8. {
  9. partial class AsyncObservable
  10. {
  11. public static IAsyncObservable<TSource> Amb<TSource>(this IAsyncObservable<TSource> first, IAsyncObservable<TSource> second)
  12. {
  13. if (first == null)
  14. throw new ArgumentNullException(nameof(first));
  15. if (second == null)
  16. throw new ArgumentNullException(nameof(second));
  17. return Create<TSource>(async observer =>
  18. {
  19. IAsyncDisposable firstSubscription = null;
  20. IAsyncDisposable secondSubscription = null;
  21. var (firstObserver, secondObserver) = AsyncObserver.Amb(observer, firstSubscription, secondSubscription);
  22. var firstTask = first.SubscribeAsync(firstObserver);
  23. var secondTask = second.SubscribeAsync(secondObserver);
  24. var d1 = await firstTask.ConfigureAwait(false);
  25. var d2 = await secondTask.ConfigureAwait(false);
  26. return StableCompositeAsyncDisposable.Create(d1, d2);
  27. });
  28. }
  29. }
  30. partial class AsyncObserver
  31. {
  32. public static (IAsyncObserver<TSource>, IAsyncObserver<TSource>) Amb<TSource>(IAsyncObserver<TSource> observer, IAsyncDisposable first, IAsyncDisposable second)
  33. {
  34. if (observer == null)
  35. throw new ArgumentNullException(nameof(observer));
  36. if (first == null)
  37. throw new ArgumentNullException(nameof(first));
  38. if (second == null)
  39. throw new ArgumentNullException(nameof(second));
  40. var gate = new AsyncLock();
  41. return
  42. (
  43. Create<TSource>(
  44. async x =>
  45. {
  46. using (await gate.LockAsync().ConfigureAwait(false))
  47. {
  48. }
  49. },
  50. async ex =>
  51. {
  52. using (await gate.LockAsync().ConfigureAwait(false))
  53. {
  54. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  55. }
  56. },
  57. async () =>
  58. {
  59. using (await gate.LockAsync().ConfigureAwait(false))
  60. {
  61. }
  62. }
  63. ),
  64. Create<TSource>(
  65. async x =>
  66. {
  67. using (await gate.LockAsync().ConfigureAwait(false))
  68. {
  69. }
  70. },
  71. async ex =>
  72. {
  73. using (await gate.LockAsync().ConfigureAwait(false))
  74. {
  75. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  76. }
  77. },
  78. async () =>
  79. {
  80. using (await gate.LockAsync().ConfigureAwait(false))
  81. {
  82. }
  83. }
  84. )
  85. );
  86. }
  87. }
  88. }