Subscribe to different event buses of the same class
I’m using 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 question is when to call :
MyPublisher.sendEvent(new OtherLoggingEvent(varA, varB, varC));
Both subscribers were called, I don’t understand why. I think this might have something to do with the fact that OtherLoggingEvent
is a subclass of LoggingEvent
, but I’m not sure. Then my question becomes how to maintain a 1-1 relationship with publishers and subscribers. I want to call:
MyPublisher.sendEvent(new OtherLoggingEvent(varA, varB, varC));
And let the subscriber public void onEvent (OtherLoggingEvent event)
call, when I call:
MyPublisher.sendEvent(new LoggingEvent(varD, varE, varF));
Subscribers:
public void onEvent(LoggingEvent event)
Will it be called? This would work as-is, but must the classes be unique and not subclasses of each other? Do I have to create a new EventBus
object?
Solution
Because of event class inheritance, both subscribers are called. However, you can turn off this eventInheritance
feature in the EventBus itself. By using this method:
EventBus BUS = EventBus.builder().eventInheritance(false).installDefaultEventBus();