本文介绍了Android Rxjava订阅变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习观察者模式,我希望我的观察者能够在某个变量更改其值时跟踪它,并进行一些操作,我已经做了类似的事情:
I am learning Observer pattern, I want my observable to keep track of a certain variable when it changes it's value and do some operations, I've done something like :
public class Test extends MyChildActivity {
private int VARIABLE_TO_OBSERVE = 0;
Observable<Integer> mObservable = Observable.just(VARIABLE_TO_OBSERVE);
protected void onCreate() {/*onCreate method*/
super();
setContentView();
method();
changeVariable();
}
public void changeVariable() {
VARIABLE_TO_OBSERVE = 1;
}
public void method() {
mObservable.map(value -> {
if (value == 1) doMethod2();
return String.valueOf(value);
}).subScribe(string -> System.out.println(string));
}
public void doMethod2() {/*Do additional operations*/}
}
但是doMethod2()没有被调用
But doMethod2() doesn't get called
推荐答案
生活中没有什么神奇的东西:如果更新值,则不会通知您的Observable
.您必须自己做.例如,使用PublishSubject
.
Nothing is magic in the life : if you update a value, your Observable
won't be notified. You have to do it by yourself. For example using a PublishSubject
.
public class Test extends MyChildActivity {
private int VARIABLE_TO_OBSERVE = 0;
Subject<Integer> mObservable = PublishSubject.create();
protected void onCreate() {/*onCreate method*/
super();
setContentView();
method();
changeVariable();
}
public void changeVariable() {
VARIABLE_TO_OBSERVE = 1;
// notify the Observable that the value just change
mObservable.onNext(VARIABLE_TO_OBSERVE);
}
public void method() {
mObservable.map(value -> {
if (value == 1) doMethod2();
return String.valueOf(value);
}).subScribe(string -> System.out.println(string));
}
public void doMethod2() {/*Do additional operations*/}
}
这篇关于Android Rxjava订阅变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!