I'm using Otto event bus in my Android app. I've read the GitHub documentation and various questions posted online about how hierarchy traverse is working:
"Registering will only find methods on the immediate class type. Unlike the Guava event bus, Otto will not traverse the class hierarchy and add methods from base classes or interfaces that are annotated"
I understand if I register a bus on a child class, then methods from the base class will not be added. So my question is, can I register a bus in a child class and register another bus in the base class?
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
}
Will both of the baseAnswerAvailable and answerAvailable methods get called?
the answer is yes actually, and here is the way
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With