Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Observable subject hot and cold

I often have the situation where I want a UI element to "watch" an underlying value - supposing I am displaying an int - I want an an IObservable that I can subscribe to.

I have been using a Subject underneath, so I can just set it. That works really well... except for the first time. If I setup the subject - then later subscribe to it by opening a new UI element - it doesn't trigger an onnext until the next change.

I basically want something that works like a subject - but always and immediately does an onNext of the latest value to any new subscribers.

I know I can write such a construct myself - but it seems a common use case - is there something standard I'm missing?

like image 345
Darren Oakey Avatar asked Oct 30 '25 21:10

Darren Oakey


1 Answers

You want either BehaviorSubject<T> or ReplaySubject<T>.

BehaviorSubject<T> replays the single most recent value and requires that you give an initial value in the constructor.

You use it like this:

var bs = new BehaviorSubject<int>(0);
bs.Subscribe(x => Console.WriteLine(x));
bs.OnNext(42);
bs.Subscribe(x => Console.WriteLine(x));

That would output 0, then 42, then 42 to the console.

ReplaySubject<T> is a little more general. It allows you to specify the number of values to replay, but doesn't enforce that you provide an initial value.

var rs = new ReplaySubject<int>(1);
rs.Subscribe(x => Console.WriteLine(x));
rs.OnNext(42);
rs.Subscribe(x => Console.WriteLine(x));

This produces 42, and then 42 to the console.

Compare this to a standard Subject<T>.

var s = new Subject<int>();
s.Subscribe(x => Console.WriteLine(x));
s.OnNext(42);
s.Subscribe(x => Console.WriteLine(x));

That just produces 42.

like image 67
Enigmativity Avatar answered Nov 02 '25 10:11

Enigmativity