我可以在基础班和儿童班上注册 Otto 巴士吗?

Lou*_*rda 5 android otto

我在我的 Android 应用程序中使用 Otto 事件总线。我已经阅读了 GitHub 文档和在线发布的关于层次遍历如何工作的各种问题:

“注册只会在直接类类型上查找方法。与 Guava 事件总线不同,Otto 不会遍历类层次结构并从被注解的基类或接口添加方法”

我知道如果我在子类上注册总线,则不会添加基类中的方法。所以我的问题是,我可以在子类中注册一个总线并在基类中注册另一个总线吗?

public class BaseActivity extends Activity
    ...
    baseBus.register(this);

    @Subscribe public void baseAnswerAvailable(BaseAnswerAvailableEvent event) {
        // TODO: React to the event somehow in the base class
    }

public class MainActivity extends BaseActivity
    ...
    bus.register(this);

    @Subscribe public void answerAvailable(AnswerAvailableEvent event) {
        // TODO: React to the event somehow
    }
Run Code Online (Sandbox Code Playgroud)

baseAnswerAvailable 和 answerAvailable 方法都会被调用吗?

Mus*_*ven 5

答案是肯定的,这是方法

https://github.com/square/otto/issues/26#issuecomment-33891598

public class ParentActivity extends Activity {
protected Object busEventListener;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

     busEventListener = new Object() {
        @Subscribe
        public void onReceiveLoginEvent(final LoginEvent event) {
            ParentActivity.this.onReceiveLoginEvent(event);
        }
        @Subscribe
        public void onReceiveLogoutEvent(final LogoutEvent event) {
            ParentActivity.this.onReceiveLogoutEvent(event);
        }
    };

    BusProvider.getInstance().register(busEventListener);
}

//subclasses extend me. This can be abstract, if necessary.
protected void onReceiveLoginEvent(final LoginEvent event) {
    Log.d("Tag", "LoginEvent");
}

//subclasses extend me. This can be abstract, if necessary.
protected void onReceiveLogoutEvent(final LogoutEvent event) {
    Log.d("Tag", "LogoutEvent");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    BusProvider.getInstance().unregister(busEventListener);
}
}
Run Code Online (Sandbox Code Playgroud)


Lou*_*rda 1

通常不会回答我未回答的问题,但因为有人赞成我的问题,我觉得这会有所帮助。我尝试为儿童和基类制作活动:

@Produce
public BaseAnswerAvailableEvent baseAnswerAvailableEvent() {
    return new BaseAnswerAvailableEvent(message);
}

@Produce
public AnswerAvailableEvent answerAvailableEvent() {
    return new AnswerAvailableEvent(message);
}
Run Code Online (Sandbox Code Playgroud)

答案是否定的,您不能在基类和子类中生成和订阅单独的事件。我生成了这两个事件,并且只有子类中的 AnswerAvailableEvent 收到了事件。