RefCount.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  22. {
  23. var sink = new _(observer, cancel);
  24. setSink(sink);
  25. return sink.Run(this);
  26. }
  27. private sealed class _ : Sink<TSource>, IObserver<TSource>
  28. {
  29. public _(IObserver<TSource> observer, IDisposable cancel)
  30. : base(observer, cancel)
  31. {
  32. }
  33. public IDisposable Run(RefCount<TSource> parent)
  34. {
  35. var subscription = parent._source.SubscribeSafe(this);
  36. lock (parent._gate)
  37. {
  38. if (++parent._count == 1)
  39. {
  40. parent._connectableSubscription = parent._source.Connect();
  41. }
  42. }
  43. return Disposable.Create(() =>
  44. {
  45. subscription.Dispose();
  46. lock (parent._gate)
  47. {
  48. if (--parent._count == 0)
  49. {
  50. parent._connectableSubscription.Dispose();
  51. }
  52. }
  53. });
  54. }
  55. public void OnNext(TSource value)
  56. {
  57. base._observer.OnNext(value);
  58. }
  59. public void OnError(Exception error)
  60. {
  61. base._observer.OnError(error);
  62. base.Dispose();
  63. }
  64. public void OnCompleted()
  65. {
  66. base._observer.OnCompleted();
  67. base.Dispose();
  68. }
  69. }
  70. }
  71. }