Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 942
Karate_Dog Avatar asked Aug 03 '16 08:08

Karate_Dog


2 Answers

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

 }
like image 110
dwursteisen Avatar answered Oct 27 '22 00:10

dwursteisen


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!"
like image 26
Dario Pellegrini Avatar answered Oct 27 '22 00:10

Dario Pellegrini