我们可以使用 RxJava 检测类成员值是否被更改吗?假设在一个类中有一个变量 var,现在我们可以在使用 RxJava 时每当 var 的值发生变化时得到通知。
最佳答案
你可以这样使用:
private final BehaviorSubject<Integer> subject = BehaviorSubject.create();
private Integer value=0;
public Observable<Integer> getUiElementAsObservable() {
return subject;
}
public void updateUiElementValue(final Integer valueAdded) {
synchronized (value) {
if (valueAdded == 0)
return;
value += valueAdded;
subject.onNext(value);
}
}
然后像这样订阅它:
compositeSubscription.add(yourClass.getUiElementAsObservable()
.subscribe(new Action1<Integer>() {
@Override
public void call(Integer userMessage) {
setViews(userMessage,true);
}
}));
您必须为所有您想要的变量创建 setter 来订阅它们的更改,并在应用更改时调用 onNext。
更新
When an observer subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable
您可以在这里查看其他类型的主题:http://reactivex.io/documentation/subject.html
一些有用的链接:
关于响应式(Reactive)编程:https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
关于 rxjava:https://youtu.be/k3D0cWyNno4
关于java - 使用 Rxjava 检测值变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203152/