Search code examples
javaandroidotto

Otto EventBus: Event fired multiple times


I am using the Otto event bus in my android application and have the problems that identical events get fired multiple times (event.hashCode() returns the same integer). The code I use to fire the events looks like this (simplified):

public class MyFragment extends MyCustomFragment {
    @Inject Bus eventBus;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        App.getComponent(getActivity()).inject(this); // use dagger to inject the event bus
    }


    // called from within `onOptionsItemSelected`
    public void handleOptionsItemXy() {
        AlertDialog.Builder a = new AlertDialog.Builder(getActivity())
            // ...
            .setPositiveButton(R.string.button_label_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // EVENT IS FIRED HERE
                    Log.d("INFO", "This log message is only displayed once!");
                    eventBus.post(new Event(EVENT_DATA));
                }
            });
    }
}

I then have a class to handle the event like this, which is created in my MainActivity.onCreate:

public class StuffManager {
    @Inject Bus bus;

    public StuffManager(Activity ctx) {
        App.getComponent(ctx).inject(this);
        bus.register(this);
    }

    @Subscribe
    public void manageStuff(Event event) {
        Log.d("SYNC", "Some event needs to be managed");
        Log.d("SYNC", "HASH: " + event.hashCode());
    }
}

The log message is only shown once and the event is only ever created at that specific location. It appears that there is something unexpected happening inside the .post method provided by the event bus.

How does this happen? What can I do to prevent it?


Solution

  • The problem was not that the event was actually fired multiple times, but that the handler was invoked multiple times. As seen in the code above, the bus.register method is called everytime I create the object; because of the activities lifecycle, this happened multiple times, causing the handler to be invoked multiple times.

    Thanks to jonk for leading me on the right path.