How do I determine how many / clear subscribers there are on an IObservable<T>?
I'm wondering if there's a way to figure out how many observers there are subscribed to an IObservable object.
I've got a class that manages a HashTable of filtered IObservable instances, and I'd like to implement a "health check" routine that can determine if subscribers have been removed / disposed, without each subscriber having to explicitly notify this class that they're finished (i.e. should be implicit vi开发者_StackOverflowa Dispose() or Unsubscribe()).
This doesn't really answer the question -
should-i-use-listiobserver-or-simply-actiont-to-keep-track-of-an-iobservable
Any ideas Rx experts?
There's nothing built in, but you could implement a CountingSubject<T>
:
public class CountingSubject<T>
{
private ISubject<T> internalSubject;
private int subscriberCount;
public CountingSubject()
: this(new Subject<T>())
{
}
public CountingSubject(ISubject<T> internalSubject)
{
this.internalSubject = internalSubject;
}
public IDisposable Subscribe(IObserver<T> observer)
{
Interlocked.Increment(ref subscriberCount);
return new CompositeDisposable(
this.internalSubject.Subscribe(observer),
Disposable.Create(() => Interlocked.Decrement(ref subscriberCount))
});
}
public int SubscriberCount
{
get { return subscriberCount; }
}
}
Since IObservable<T>
only supplies a single method, Subscribe
, there's no way you can get the count of subscribers from it. The subscriber list is an implementation detail that's not exposed through this interface.
In order to get the count, whatever class implements the IObservable
interface would have to expose a property or method to get the count, and the client code would have to cast the IObservable
reference to that type, and then access the property or method.
精彩评论