Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 via 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?

like image 846
Chris Webb Avatar asked Dec 01 '25 20:12

Chris Webb


1 Answers

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; }
    }
}
like image 73
Richard Szalay Avatar answered Dec 04 '25 08:12

Richard Szalay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!