1
0

RefCount.cs 2.6 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.Reactive.Subjects;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. internal sealed class RefCount<TSource> : Producer<TSource>
  9. {
  10. private readonly IConnectableObservable<TSource> _source;
  11. private readonly object _gate;
  12. private int _count;
  13. private IDisposable _connectableSubscription;
  14. public RefCount(IConnectableObservable<TSource> source)
  15. {
  16. _source = source;
  17. _gate = new object();
  18. _count = 0;
  19. _connectableSubscription = default(IDisposable);
  20. }
  21. protected override IDisposable CreateSink(IObserver<TSource> observer, IDisposable cancel) => new _(observer, cancel);
  22. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  23. {
  24. var sink = new _(observer, cancel);
  25. setSink(sink);
  26. return sink.Run(this);
  27. }
  28. private sealed class _ : Sink<TSource>, IObserver<TSource>
  29. {
  30. public _(IObserver<TSource> observer, IDisposable cancel)
  31. : base(observer, cancel)
  32. {
  33. }
  34. public IDisposable Run(RefCount<TSource> parent)
  35. {
  36. var subscription = parent._source.SubscribeSafe(this);
  37. lock (parent._gate)
  38. {
  39. if (++parent._count == 1)
  40. {
  41. parent._connectableSubscription = parent._source.Connect();
  42. }
  43. }
  44. return Disposable.Create(() =>
  45. {
  46. subscription.Dispose();
  47. lock (parent._gate)
  48. {
  49. if (--parent._count == 0)
  50. {
  51. parent._connectableSubscription.Dispose();
  52. }
  53. }
  54. });
  55. }
  56. public void OnNext(TSource value)
  57. {
  58. base._observer.OnNext(value);
  59. }
  60. public void OnError(Exception error)
  61. {
  62. base._observer.OnError(error);
  63. base.Dispose();
  64. }
  65. public void OnCompleted()
  66. {
  67. base._observer.OnCompleted();
  68. base.Dispose();
  69. }
  70. }
  71. }
  72. }