Question

So I have a BehaviorSubject<string> which I wish to use for a property. I have been using the blocking First() method to get the current value that the BehaviorSubject holds in a property getter.

The First() operation is now obsolete, so what is the new way to achieve this?

Was it helpful?

Solution 2

With BehaviorSubject<T> you are guaranteed* to have a First value always available.

However, IObservable<T> query operators can't work under that assumption in general, so the Obsolete attribute was added to drive people towards asynchronous methods like FirstAsync - helping them to "fall into the pit of success".

Because of the special case of BehaviorSubject<T> always having a value set, it has a thread safe Value property. So, assuming that you have something like this:

var subject = new BehaviorSubject<string>("Some value");

Then you can do this:

var current = subject.Value;

*Attempting to acess the value of a BehaviorSubject<T> instance after its Dispose method has been called, whether by the Value property or a query operator like FirstAsync, will cause an ObjectDisposedException to be thrown.

OTHER TIPS

James's answer is great, but I thought it worth mentioning the general alternatives to First that works for any IObservable. But definitely use the Value property if you know it is a BehaviorSubject.

// synchronously wait for the value
var value = someObservable.FirstAsync().Wait();

// async await
var value = await someObservable.FirstAsync();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top