Reputation: 1167
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?
Upvotes: 0
Views: 2510
Reputation: 9
This is happening with me too. I have some fragments using the same fragment class saying StuffFragment and I create two instances of StuffFragment. So because I subscribed Otto bus in StuffFragment class. The post method happens once and the actual event is fired once. But since there are two instances so it will do the same stuff when receiving the event which looks like we received two events.
Upvotes: -1
Reputation: 1167
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.
Upvotes: 4