SubscribeOn.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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.Concurrency;
  5. using System.Reactive.Disposables;
  6. namespace System.Reactive.Linq
  7. {
  8. // REVIEW: Consider more fine-grained control over subscribe and dispose schedulers.
  9. partial class AsyncObservable
  10. {
  11. public static IAsyncObservable<TSource> SubscribeOn<TSource>(this IAsyncObservable<TSource> source, IAsyncScheduler scheduler)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. if (scheduler == null)
  16. throw new ArgumentNullException(nameof(scheduler));
  17. return Create<TSource>(async observer =>
  18. {
  19. var m = new SingleAssignmentAsyncDisposable();
  20. var d = new SerialAsyncDisposable();
  21. await d.AssignAsync(m).ConfigureAwait(false);
  22. var scheduled = await scheduler.ScheduleAsync(async ct =>
  23. {
  24. var subscription = await source.SubscribeSafeAsync(observer).RendezVous(scheduler, ct);
  25. var scheduledDispose = AsyncDisposable.Create(async () =>
  26. {
  27. await scheduler.ScheduleAsync(async _ =>
  28. {
  29. await subscription.DisposeAsync().RendezVous(scheduler, ct);
  30. }).ConfigureAwait(false);
  31. });
  32. await d.AssignAsync(scheduledDispose).RendezVous(scheduler, ct);
  33. }).ConfigureAwait(false);
  34. await m.AssignAsync(scheduled).ConfigureAwait(false);
  35. return d;
  36. });
  37. }
  38. }
  39. }