3

有什么方法可以暂停来自番石榴库的 EventBus 事件发布。

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

最后一次changeSomething()执行后,我想告诉番石榴恢复事件处理。

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

4

1 回答 1

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);
            }
        }
    }
于 2012-11-08T12:15:11.607 回答