3

I am using the GreenRobot Event Bus 3.0 as an event bus and I have 2 publishers:

 private static final EventBus EVENT_BUS = new EventBus();

//Publish event to the event bus
public static void sendEvent(LoggingEvent event){
    LogPublisher.EVENT_BUS.post(event);
}

//Publish event to the event bus
public static void sendEvent(OtherLoggingEvent event){
    LogPublisher.EVENT_BUS.post(event);
}

I have 2 subscribers:

 @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onEvent(LoggingEvent event){
        logEvent( event);
    }

 @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onEvent(OtherLoggingEvent event){
        logEvent( event);
    }

The issue is when make a call like:

MyPublisher.sendEvent(new OtherLoggingEvent(varA, varB, varC));

Both subscribers are called and I can't figure out why. I think it might have something to do with the fact that OtherLoggingEvent is a subclass of LoggingEvent, but I'm not sure. My question then becomes how do I maintain a 1-1 relationship with the publisher and subscriber. I want to call:

MyPublisher.sendEvent(new OtherLoggingEvent(varA, varB, varC));

and have the subscriber public void onEvent(OtherLoggingEvent event) called and when I call:

MyPublisher.sendEvent(new LoggingEvent(varD, varE, varF));

the subscriber:

 public void onEvent(LoggingEvent event)

will be called? Will this work as is, but have to make sure that the classes are unique, and not a subclass of each other? Do I have to create a new EventBus object?

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156

1 Answers1

4

Both subscribers calling because of the event class inheritance. But you can switch off this eventInheritance feature in EventBus itself. By using this method:

EventBus BUS = EventBus.builder().eventInheritance(false).installDefaultEventBus();
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
Krish
  • 3,860
  • 1
  • 19
  • 32
  • This is perfect! Thank you! I thought it might have something to do with the fact that one of the subscribing classes inherited from the other. This worked like a charm, just the way I need it to. – BlackHatSamurai Apr 07 '17 at 08:30