Android Rxjava subscribe to a variable change

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

 }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)