我正在学习观察者模式,我希望我的观察者能够在某个变量更改其值并进行一些操作时对其进行跟踪,我已经做了一些类似的事情:

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()不会被调用

最佳答案

生活中没有什么神奇的东西:如果更新值,则不会通知您的Observable。您必须自己做。例如,使用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*/}

 }

09-11 22:20