hatellla
hatellla

Reputation: 5132

Guava EventBus Multiple subscribers same tpe

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class Test {

    public static class Processing { }
    public static class ProcessingResults { }
    public static class ProcessingFinished { }

    public static EventBus bus = new EventBus();

    @Subscribe
    public void receiveStartRequest(Processing evt) {
        System.out.println("Got processing request - starting processing");
    }

    @Subscribe
    public void processingStarted(Processing evt) {
        System.out.println("Processing has started");
    }

    @Subscribe
    public void resultsReceived(ProcessingResults evt) {
        System.out.println("got results");
    }

    @Subscribe
    public void processingComplete(ProcessingFinished evt) {
        System.out.println("Processing has completed");
    }


    public static void main(String[] args) {
        Test t = new Test();
        bus.register(t);
        bus.post(new Processing());
    }
}

So, in above example, it can be seen that there are 2 subscribers accepting same type Processing. Now, at the time of post(), which all functions will get called? If the 2 functions receiveStartRequest and processingStarted will get called, then in which order they will be get called?

Upvotes: 2

Views: 1452

Answers (1)

Olivier Grégoire
Olivier Grégoire

Reputation: 35427

Both your methods will be called and in no predefinite order.

To counter this, just create two extra classes: ProcessingStarted and ProcessingRequested.

public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}


public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}

Then call post(new ProcessingRequested(processing)) and post(new ProcessingStarted(processing)) when needed, instead of a single post(processing).

Upvotes: 5

Related Questions