Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

rx java - Android Rxjava subscribe to a variable change

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*/}

}

But doMethod2() doesn't get called

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If interested here a Kotlin version of Variable class, which lets subscribers to be updated after every variable change.

class Variable<T>(private val defaultValue: T) {
var value: T = defaultValue
    set(value) {
        field = value
        observable.onNext(value)
    }
val observable = BehaviorSubject.createDefault(value)
}

Usage:

val greeting = Variable("Hello!")
greeting.observable.subscribe { Log.i("RxKotlin", it) }
greeting.value = "Ciao!"
greeting.value = "Hola!"

This will print:

"Hello!"
"Ciao!"
"Hola!"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...