订阅同一班级的不同活动巴士

时间:2017-04-07 05:22:59

标签: java android greenrobot-eventbus-3.0

我使用GreenRobot Event Bus 3.0作为活动总线,我有2个发布商:

 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);
}

我有2个订阅者:

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

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

问题在于拨打电话时如下:

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

两个订阅者都被调用,我无法弄清楚原因。我认为它可能与OtherLoggingEventLoggingEvent的子类这一事实有关,但我不确定。那么我的问题就是如何与发布者和订阅者建立1-1关系。我想打电话:

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

并调用订阅者public void onEvent(OtherLoggingEvent event),当我致电时:

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

订阅者:

 public void onEvent(LoggingEvent event)
会被叫到吗?这是否可以正常工作,但必须确保这些类是唯一的,而不是彼此的子类?我是否必须创建一个新的EventBus对象?

1 个答案:

答案 0 :(得分:4)

两个订阅者都因为事件类继承而调用。但您可以在EventBus中关闭此eventInheritance功能。通过使用此方法:

EventBus BUS = EventBus.builder().eventInheritance(false).installDefaultEventBus();