Bryan Anderson
Bryan Anderson

Reputation: 16129

How do I provide the latest value of a hot observable on subscribe

I have a hot observable (from an event) that I'm calling DistinctUntilChanged on which will have multiple subscribers who will subscribe at different times after the observable has started running and produced its first value. Subscribers will get getting the IObservable through a property on my class.

How do I make it so that each time someone subscribes to the observable they get the last value published but the observable acts normally otherwise? I think I might be looking for PublishLast but I'm not sure if it has other side effects.

Similar question: How do I get an IObservable to push the newest value upon subscription? This is a very similar question but it's from over a year ago and a lot of additions have been made to Rx so I think there might be a built-in function now rather than having to rely on a BehaviorSubject so I don't think this is an exact duplicate.

Edit: Here is what I'm actually trying to do. There's a comment below the actual observable sequence I'm talking about.

Upvotes: 13

Views: 4429

Answers (1)

Lee Campbell
Lee Campbell

Reputation: 10783

The other answer was close. You either want a ReplaySubject(1) ie only replay 1 value; or you want a BehaviorSubject. The difference is a Behavior Subject will require a default value. This will also guarantee that the subscriber will always get a value immediately.

var replay1 = source.Replay(1);
replay1.Connect();
//Or
var alwaysHaveValue = source.Multicast(new BehaviorSubject<int>(-1));

To understand each of the Subjects check out my Intro to Rx post

Upvotes: 9

Related Questions