Search code examples
javaobservablerx-javarx-java2

RxJava: How to subscribe to the events of a different class


I have a question about how to conceptually create an Observer and link it to another class: I currently have a class called Simulation that is supposed to create TransactionCreated objects and publish them as events. Another class called TransactionReceiver is supposed to be an Observer of every event that is published by the Simulation class and work with them. The main method is included in the Simulation class and starts by creating an event in a static context and publishing it which works. My question would be how I am supposed to connect the TransactionReceiver as an Observer and let it subscribe to those events by receiving them in a method and work with those received objects? Do I need to create another class that would include the main method and create a Simulation and TransactionReceiver object that are then linked together as Observable and Observer? How would that look like? And if I would extend that system with several different classes would they all have to be linked together through one class that connects Observers and Observables?


Solution

  • Your app should only have one main method.

    Conceptually, this should be where you do the initial setup of Simulation and TransactionReceiver, so perhaps you could move it to a separate class to help you visualise how things should work. You could try something like below:

    class Application {
       private Simulation simulation;
       private TransactionReceiver transactionReceiver;
    
       public Application() {
           simulation = new Simulation(/* params here*/);
           transactionReceiver = new TransactionReceiver(/*params here*/);
       }
    
       public void go() {
           simulation.simulate().subscribe(transactionCreated -> transactionReceiver.doSomething(transactionCreated);
       }
    
       public static final main(String[] args) {
           Application application = new Application();  
           application.go();
       } 
    }
    

    Eventually as you get more fluent you could think about adding a dependency-injection framework like Guice or Dagger.

    This will help you with managing the dependencies of the classes that you need to use throughout your application.

    So you would end up with a more simple Application - it would just set up the DI-framework and then you can use the classes how you want to.

    UPDATE:

    If you want to communicate between two different classes, you will need to use methods:

    class Simulation {
        public Observable<TransactionCreated> simulate() {
            // use PublishSubject or whatever 
        }
    }