BehaviorSubject<T> 作为支持字段?
BehaviorSubject<T> as backing field?
在Intro to Rx中是这样说的:
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.
但是我真的找不到一个清楚的例子来说明如何做到这一点。
如果我理解正确的话,建议是这样的:
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(); }
}
我对此有几个问题:
- 这确实是提议的内容吗?
- 是否有此模式的通用名称,我可以进一步 Google?因为我不知道该怎么称呼它,所以我的搜索结果很短。
- 这被认为是好的做法吗?或者是否有更好的方法来做同样的事情(即创建一个可观察的场)?
- 您对此的命名约定有何建议?
我一直认为它是 INotifyPropertyChanged
的可观察版本,如:
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);
}
}
然后:
var subscription = _myNumberChanged.Subscribe(i => { });
在Intro to Rx中是这样说的:
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.
但是我真的找不到一个清楚的例子来说明如何做到这一点。
如果我理解正确的话,建议是这样的:
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(); }
}
我对此有几个问题:
- 这确实是提议的内容吗?
- 是否有此模式的通用名称,我可以进一步 Google?因为我不知道该怎么称呼它,所以我的搜索结果很短。
- 这被认为是好的做法吗?或者是否有更好的方法来做同样的事情(即创建一个可观察的场)?
- 您对此的命名约定有何建议?
我一直认为它是 INotifyPropertyChanged
的可观察版本,如:
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);
}
}
然后:
var subscription = _myNumberChanged.Subscribe(i => { });