Otto EventBus:多次触发事件

Otto EventBus: Event fired multiple times

我在我的 android 应用程序中使用 Otto 事件总线并且遇到相同事件被多次触发的问题(event.hashCode() returns 相同的整数)。我用来触发事件的代码如下所示(简化):

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));
                }
            });
    }
}

然后我有一个 class 来处理这样的事件,它是在我的 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());
    }
}

日志消息只显示一次,事件只会在该特定位置创建。事件总线提供的 .post 方法 内部 似乎发生了意想不到的事情。

这是怎么发生的?我能做些什么来防止它?

问题不在于该事件实际上 触发了 多次,而是该处理程序被多次调用。如上面的代码所示,每次创建对象时都会调用 bus.register 方法;由于活动生命周期的原因,这种情况发生了多次,导致处理程序被多次调用。

感谢jonk带领我走上了正确的道路。

这也发生在我身上。我有一些片段使用相同的片段 class 说 StuffFragment,我创建了两个 StuffFragment 实例。所以因为我在 StuffFragment class 订阅了 Otto 总线。 post 方法发生一次,实际事件被触发一次。但是因为有两个实例,所以它在接收事件时会做同样的事情,看起来我们收到了两个事件。