4

In Intro to Rx the following is said:

BehaviorSubjects are often associated with class properties. As they always have a value and can provide change notifications, they could be candidates for backing fields to properties.

However I couldn't really find a clear example of how to do this.

If I understand this correctly, something like this is proposed:

private BehaviorSubject<int> _myNumber = new BehaviorSubject<int>(0);
public int MyNumber
{
    get { return _myNumber.Value; } // optional
    set { _myNumber.OnNext(value); }
}
public IObservable MyNumbers
{
    get { return _myNumber.AsObservable(); }
}

I have several questions about this:

  • Is this indeed what is being proposed?
  • Is there a general name for this pattern, something I could Google further? As I didn't know what to call it and my searches came up short.
  • Is this considered good practice? Or are there better ways of doing the same (i.e. kind of creating an observable field)?
  • What would you suggest as a naming convention for this?
The Oddler
  • 6,314
  • 7
  • 51
  • 94

1 Answers1

1

I always though of it as an observable version of INotifyPropertyChanged, as in:

private BehaviorSubject<int> _myNumberChanged = new BehaviorSubject<int>(0);
private int _myNumber;
public int MyNumber
{
    get => _myNumber;
    set
    {
        if (_myNumber == value)
        {
            return;
        }

        _myNumber = value;
        _myNumberChanged.OnNext(_myNumber);
    }
}

And then:

var subscription = _myNumberChanged.Subscribe(i => { });
Aaron
  • 622
  • 7
  • 15