Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I register an Otto bus on both base and child class?

Tags:

android

otto

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?

like image 441
Lou Morda Avatar asked Dec 20 '15 21:12

Lou Morda


1 Answers

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);
}
}
like image 199
Mustafa Güven Avatar answered Sep 20 '22 13:09

Mustafa Güven