今天,当学习ReactiveX API时,我创建了一个类似于以下的帮助器类ObservedVariable:
class ObservedVariable<T> {
private T variable;
private Subject<T> subject = new Subject<T>();
public ObservedVariable(T variable) { this.variable = variable; }
public IObservable<T> get() { return subject.AsObservable(); }
public void get(Action<T> onChange) {
get().Subscribe(onChange);
onChange(variable);
}
public void set(T newValue) {
variable = newValue;
subject.OnNext(variable);
}
}
class MyUserModel {
public ObservedVariable<string> userName = new ObservedVariable<string>("Carl");
}
private void exampleOfAnObservedVar() {
var viewThatIsAutomaticallyUpdated = GetComponent<Text>();
var exampleUser = new MyUserModel();
exampleUser.userName.get(userName => { viewThatIsAutomaticallyUpdated.text = userName; });
exampleUser.userName.set("Caaaarl");
}
然后我发现BehaviorSubject已经完全按照我的ObservedVariable实现实现了预期目的,并将示例更改为:
public static class BehaviorSubjectExtensions {
public static void get<T>(this BehaviorSubject<T> self, Action<T> onChange) { self.Subscribe(onChange); }
public static void set<T>(this BehaviorSubject<T> self, T newValue) { self.OnNext(newValue); }
}
class MyUserModel {
public BehaviorSubject<string> userName = new BehaviorSubject<string>("Carl");
}
private void exampleOfAnObservedVar() {
var viewThatIsAutomaticallyUpdated = GetComponent<Text>();
var exampleUser = new MyUserModel();
exampleUser.userName.get(userName => { viewThatIsAutomaticallyUpdated.text = userName; });
exampleUser.userName.set("Caaaarl");
}
我的主要问题是:如果我没有将BehaviorSubject直接放在数据模型中,那么我有一个重复的状态,因此如果我想使用这种反应性字段,建议直接在datamodel层中使用BehaviorSubject(s)吗?