Reputation: 66531
I have a mildly 'expensive' calculation exposed through an IObservable property.
I want to protect it from being run multiple times if there are multiple subscribers, so I put a Publish().RefCount() behind it, but when I stick breakpoints in, I still see it getting called twice.
public IObservable<int> Property
{
get { return _Source.Select(Expensive).Publish().RefCount(); }
}
Upvotes: 2
Views: 191
Reputation: 66531
It's only the result of Publish().RefCount()
which is 'protected', not your source - as it stands, if you have multiple calls to your property, you will get multiple independent 'protected' observables - which will each subscribe independently to your source.
You need a backing field, which you can ensure will only be defined once:
private IObservable<int> _Property;
public IObservable<int> { get { return _Property; } }
//elsewhere:
_Property = _Source.Select(Expensive).Publish().RefCount()
(or alternatively)
public IObservable<int> { get; private set; }
//elsewhere:
_Property = _Source.Select(Expensive).Publish().RefCount()
Upvotes: 10