FirstLastBlocking.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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;
  5. using System.Collections.Generic;
  6. using System.Reactive.Disposables;
  7. using System.Text;
  8. using System.Threading;
  9. namespace System.Reactive.Linq.ObservableImpl
  10. {
  11. internal abstract class BaseBlocking<T> : CountdownEvent, IObserver<T>
  12. {
  13. protected IDisposable _upstream;
  14. internal T _value;
  15. internal bool _hasValue;
  16. internal Exception _error;
  17. int once;
  18. internal BaseBlocking() : base(1) { }
  19. internal void SetUpstream(IDisposable d)
  20. {
  21. Disposable.SetSingle(ref _upstream, d);
  22. }
  23. protected void Unblock()
  24. {
  25. if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
  26. {
  27. Signal();
  28. }
  29. }
  30. public abstract void OnCompleted();
  31. public virtual void OnError(Exception error)
  32. {
  33. _value = default;
  34. _error = error;
  35. Unblock();
  36. }
  37. public abstract void OnNext(T value);
  38. public new void Dispose()
  39. {
  40. base.Dispose();
  41. if (!Disposable.GetIsDisposed(ref _upstream))
  42. {
  43. Disposable.TryDispose(ref _upstream);
  44. }
  45. }
  46. }
  47. internal sealed class FirstBlocking<T> : BaseBlocking<T>
  48. {
  49. internal FirstBlocking() : base() { }
  50. public override void OnCompleted()
  51. {
  52. Unblock();
  53. if (!Disposable.GetIsDisposed(ref _upstream))
  54. {
  55. Disposable.TryDispose(ref _upstream);
  56. }
  57. }
  58. public override void OnError(Exception error)
  59. {
  60. base.OnError(error);
  61. if (!Disposable.GetIsDisposed(ref _upstream))
  62. {
  63. Disposable.TryDispose(ref _upstream);
  64. }
  65. }
  66. public override void OnNext(T value)
  67. {
  68. if (!_hasValue)
  69. {
  70. _value = value;
  71. _hasValue = true;
  72. Disposable.TryDispose(ref _upstream);
  73. Unblock();
  74. }
  75. }
  76. }
  77. internal sealed class LastBlocking<T> : BaseBlocking<T>
  78. {
  79. internal LastBlocking() : base() { }
  80. public override void OnCompleted()
  81. {
  82. Unblock();
  83. Disposable.TryDispose(ref _upstream);
  84. }
  85. public override void OnError(Exception error)
  86. {
  87. base.OnError(error);
  88. Disposable.TryDispose(ref _upstream);
  89. }
  90. public override void OnNext(T value)
  91. {
  92. _value = value;
  93. _hasValue = true;
  94. }
  95. }
  96. }