dwynne
dwynne

Reputation: 916

Should I expose ISubject<T> or IObservable<T> and IObserver<T>?

I have a value that I want users to be able to subscribe to and push to, so internally in my class I'm using Subject<T>.

When exposing this value as a property am I best to expose it as a ISubject<T> or is it better to split ISubject<T> into IObserver<T> and IObservable<T>?

Option 1:

    private readonly ISubject<bool> isLightOn = new Subject<bool>();

    public ISubject<bool> IsLightOn
    {
        get
        {
            return this.isLightOn;
        }
    }

Option 2:

    private readonly ISubject<bool> isLightOn = new Subject<bool>();

    public IObservable<bool> IsLightOnOut
    {
        get
        {
            return this.isLightOn.AsObservable();
        }
    }

    public IObserver<bool> IsLightOnIn
    {
        get
        {
            return this.isLightOn.AsObserver();
        }
    }

Which is better and why? If option 2, any thoughts on the naming convention also welcome.

Upvotes: 1

Views: 830

Answers (1)

Richard Szalay
Richard Szalay

Reputation: 84744

Separating the two properties gives you more flexibility ('set' could write to a different subject), but the bigger question is: do you expect consumers of this class to call OnCompleted or OnError?

If not, you should expose a SetIsLightOn method that writes to the subject and expose IsLightOnValues as an IObservable<bool>

Upvotes: 1

Related Questions