ObserveOn.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. #if !NO_PERF
  5. using System;
  6. using System.Reactive.Concurrency;
  7. using System.Threading;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. class ObserveOn<TSource> : Producer<TSource>
  11. {
  12. private readonly IObservable<TSource> _source;
  13. private readonly IScheduler _scheduler;
  14. public ObserveOn(IObservable<TSource> source, IScheduler scheduler)
  15. {
  16. _source = source;
  17. _scheduler = scheduler;
  18. }
  19. #if !NO_SYNCCTX
  20. private readonly SynchronizationContext _context;
  21. public ObserveOn(IObservable<TSource> source, SynchronizationContext context)
  22. {
  23. _source = source;
  24. _context = context;
  25. }
  26. #endif
  27. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  28. {
  29. #if !NO_SYNCCTX
  30. if (_context != null)
  31. {
  32. var sink = new ObserveOnImpl(this, observer, cancel);
  33. setSink(sink);
  34. return _source.Subscribe(sink);
  35. }
  36. else
  37. #endif
  38. {
  39. var sink = new ObserveOnObserver<TSource>(_scheduler, observer, cancel);
  40. setSink(sink);
  41. return _source.Subscribe(sink);
  42. }
  43. }
  44. #if !NO_SYNCCTX
  45. class ObserveOnImpl : Sink<TSource>, IObserver<TSource>
  46. {
  47. private readonly ObserveOn<TSource> _parent;
  48. public ObserveOnImpl(ObserveOn<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  49. : base(observer, cancel)
  50. {
  51. _parent = parent;
  52. }
  53. public void OnNext(TSource value)
  54. {
  55. _parent._context.PostWithStartComplete(() =>
  56. {
  57. base._observer.OnNext(value);
  58. });
  59. }
  60. public void OnError(Exception error)
  61. {
  62. _parent._context.PostWithStartComplete(() =>
  63. {
  64. base._observer.OnError(error);
  65. base.Dispose();
  66. });
  67. }
  68. public void OnCompleted()
  69. {
  70. _parent._context.PostWithStartComplete(() =>
  71. {
  72. base._observer.OnCompleted();
  73. base.Dispose();
  74. });
  75. }
  76. }
  77. #endif
  78. }
  79. }
  80. #endif