best way to combine guava eventbus and AWT Event thread handling

牧云@^-^@ 提交于 2019-12-04 01:17:59

The handlers registered with an async event bus are executed on whatever thread the provided Executor chooses to run them on, not necessarily a worker thread.

What I've done is created an implementation of Executor that runs stuff on the event queue thread. It's pretty simple:

public class EventQueueExecutor implements Executor {
  @Override public void execute(Runnable command) {
    EventQueue.invokeLater(command);
  }
}

You can then just create your EventBus with that:

EventBus eventBus = new AsyncEventBus(new EventQueueExecutor());

Then all handlers will be executed on the event queue thread.

Edit:

An example of forwarding events:

public class EventForwarder {
  private final EventBus uiEventBus;

  public EventForwarder(EventBus uiEventBus) {
    this.uiEventBus = uiEventBus;
  }

  // forward all events
  @Subscribe
  public void forwardEvent(Object event) {
    uiEventBus.post(event);
  }

  // or if you only want a specific type of event forwarded
  @Subscribe
  public void forwardEvent(UiEvent event) {
    uiEventBus.post(event);
  }
}

Just subscribe that to your main event bus and post all events to the main event bus, but subscribe all UI components to the UI event bus.

You can create an EventBus that dispatches only on the AWT thread:

EventBus mybus = new AsyncEventBus("awt",
    new Executor() {
        public void execute (Runnable cmd) {
            if (EventQueue.isDispatchThread()) {
                cmd.run();
            } else {
                EventQueue.invokeLater(cmd);
            }
        }
    });
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!