Reputation: 23483
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?
Upvotes: 3
Views: 1694
Reputation: 3885
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();
Upvotes: 4