Guava EventBus:暂停活动发布

时间:2012-11-08 10:30:13

标签: guava

是否有任何方法可以暂停来自番石榴库的EventBus事件发布。

我有一个发布事件的方法changeSomething()(例如SomethingChangedEvent)。现在,此方法由另一个方法doStuff()在循环中调用。 问题是SomethingChangedEvent在每次调用changeSomething()时都会发布,即使只有最后一次更改很重要。由于事件的处理程序执行了一些重量级计算,因此应用程序的性能会快速下降。

在最后一次执行changeSomething()之后,我想告诉guava恢复事件处理。

有没有办法告诉番石榴忽略除最后一个之外的所有SomethingChangedEvent

1 个答案:

答案 0 :(得分:2)

我尝试了这种模式,使用子分类从毒丸模式派生出来:

 public class SomethingChangedEvent {

        private final String name;

        public SomethingChangedEvent(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }

    }

    public class IgnoreSomethingChangedEvent extends SomethingChangedEvent {
        public IgnoreSomethingChangedEvent(String name) {
            super(name);
        }

    }

    public class HandleSomethingChangedEvent extends SomethingChangedEvent {
        public HandleSomethingChangedEvent(String name) {
            super(name);
        }

    }

    private void eventBusTest() {
        EventBus eventBus = new EventBus();
        eventBus.register(new EventBusSomethingChanged());
        eventBus.post(new SomethingChangedEvent("process this one"));
        eventBus.post(new IgnoreSomethingChangedEvent("ignore"));
        eventBus.post(new SomethingChangedEvent("don't process this one"));
        eventBus.post(new HandleSomethingChangedEvent("handle"));
        eventBus.post(new SomethingChangedEvent("process this one bis"));
    }

    public class EventBusSomethingChanged {
        private boolean ignore;

        @Subscribe
        public void SomethingChanged(SomethingChangedEvent e) {
            if (e instanceof IgnoreSomethingChangedEvent) {
                ignore = true;
                return;
            }
            if (e instanceof HandleSomethingChangedEvent) {
                ignore = false;
                return;
            }
            if (!ignore) {
                System.out.println("processing:" + e);
            }
        }
    }