0

I have class three classes. Pref, ClassA, and ClassB.

public class Pref{
     public static ArrayList<Pref> prefList;
     public static Observable<ArrayList<Pref>> observable;

     public static void loadData(){
         prefList = getFromDb();
         observable = Observable.just(prefList);
    }  
}

Application runs the ClassA First.

    public ClassA{
         public ClassA(){
              initObserver();
              setObserver();
         }
         public void initObserver(){
               Pref.loadData();
         }

         public void setObserver(){
              Observer<ArrayList<Pref>> obs = new Observer() {
                @Override
                public void onSubscribe(Disposable dspsbl) {
                      System.out.println("Subscribed");
                }

              @Override
              public void onNext(ArrayList<Pref>> t) {
                    System.out.println("Loading Preference.");
                    //Need to do some other works here.
              }

              @Override
              public void onError(Throwable thrwbl) {
              }

             @Override
             public void onComplete() {
             }
          };
         Pref.observable.subscribe(obs);
     }
}

Now I want to change the list from ClassB.

     public class ClassB{
            private void changeList(){
                  Pref.prefList = loadDataFromSomeSource();
           }
     }

When I run ClassA, the System.out works fine. But when I change the list from ClassB nothing happens. My question is, is the right way to work with Rxjava. Is it for Rxjava built? If I am wrong how can I achieve this functionality? How can I write several ClassA like classes so that When the ClassB::changeList() runs, I can listen it in ClassA?

Pranjal Choladhara
  • 845
  • 2
  • 14
  • 35

1 Answers1

1

By setting Pref.prefList = loadDataFromSomeSource();, you assign a new list instance to Pref.prefList. This will not update Pref.observable in any way, because this still refers to the old Pref.prefList instance.

I also think that you can not use an Observable to publish events through it. As far as I understand your situation, you need an ObservableSource (see http://reactivex.io/RxJava/javadoc/io/reactivex/ObservableSource.html). For example, it is implemented by PublishSubject. You could use it like this:

PublishSubject<String> source = PublishSubject.create();
source.subscribe(System.out::println);
source.onNext("test 1");
source.onNext("test 2");
source.onNext("test 3");

Or, in your case: in class Pref, you can use public static PublishSubject<ArrayList<Pref>> source = PublishSubject.create();. When loading the data, you can publish the new data using onNext, like this in ClassB: Pref.source.onNext(loadDataFromSomeSource())

Sebu
  • 4,671
  • 5
  • 16
  • 29