Files

83 lines
2.2 KiB
C#
Raw Permalink Normal View History

2025-10-03 00:02:43 -04:00
using System;
namespace UniRx.Operators
{
internal class RefCountObservable<T> : OperatorObservableBase<T>
{
2026-03-20 11:56:50 -04:00
private readonly object gate = new();
private readonly IConnectableObservable<T> source;
private IDisposable connection;
private int refCount;
2025-10-03 00:02:43 -04:00
public RefCountObservable(IConnectableObservable<T> source)
: base(source.IsRequiredSubscribeOnCurrentThread())
{
this.source = source;
}
protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel)
{
return new RefCount(this, observer, cancel).Run();
}
2026-03-20 11:56:50 -04:00
private class RefCount : OperatorObserverBase<T, T>
2025-10-03 00:02:43 -04:00
{
2026-03-20 11:56:50 -04:00
private readonly RefCountObservable<T> parent;
2025-10-03 00:02:43 -04:00
2026-03-20 11:56:50 -04:00
public RefCount(RefCountObservable<T> parent, IObserver<T> observer, IDisposable cancel) : base(observer,
cancel)
2025-10-03 00:02:43 -04:00
{
this.parent = parent;
}
public IDisposable Run()
{
var subcription = parent.source.Subscribe(this);
lock (parent.gate)
{
2026-03-20 11:56:50 -04:00
if (++parent.refCount == 1) parent.connection = parent.source.Connect();
2025-10-03 00:02:43 -04:00
}
return Disposable.Create(() =>
{
subcription.Dispose();
lock (parent.gate)
{
2026-03-20 11:56:50 -04:00
if (--parent.refCount == 0) parent.connection.Dispose();
2025-10-03 00:02:43 -04:00
}
});
}
public override void OnNext(T value)
{
2026-03-20 11:56:50 -04:00
observer.OnNext(value);
2025-10-03 00:02:43 -04:00
}
public override void OnError(Exception error)
{
2026-03-20 11:56:50 -04:00
try
{
observer.OnError(error);
}
finally
{
Dispose();
}
2025-10-03 00:02:43 -04:00
}
public override void OnCompleted()
{
2026-03-20 11:56:50 -04:00
try
{
observer.OnCompleted();
}
finally
{
Dispose();
}
2025-10-03 00:02:43 -04:00
}
}
}
}