private void bindEventBuses() { // Make event buses injectable. Use EventBusProxyScope to automatically wrap the event buses injected across // scopes with ResettableEventBus final Provider<EventBus> eventBusProvider = () -> new ResettableEventBus(new SimpleEventBus()); final Function<String, Key<EventBus>> createEventBusKey = (name) -> Key.get(EventBus.class, Names.named(name)); final Consumer<String> bindEventBus = name -> bind(createEventBusKey.apply(name)) .toProvider(eventBusProvider) .in(eventBusScopes.get(name)); bindEventBus.accept(AdmincentralEventBus.NAME); bindEventBus.accept(AppEventBus.NAME); bindEventBus.accept(SubAppEventBus.NAME); bindEventBus.accept(ChooseDialogEventBus.NAME); bindEventBus.accept("mediaeditor"); }
@Override protected void configure() { Injector parentInjector = ((GuiceComponentProvider) parentComponentProvider).getInjector(); Map<Key<?>, Binding<?>> explicitBindings = parentInjector.getBindings(); for (Map.Entry<Key<?>, Binding<?>> entry : explicitBindings.entrySet()) { Key<?> key = entry.getKey(); if (key.getTypeLiteral().getRawType().equals(EventBus.class)) { Named named = (Named) key.getAnnotation(); EventBus parentEventBus = (EventBus) parentInjector.getInstance(key); ResettableEventBus resettableEventBus = new ResettableEventBus(parentEventBus); bind(EventBus.class).annotatedWith(Names.named(named.value())).toInstance(resettableEventBus); resettableEventBuses.add(resettableEventBus); } } }
@Override protected <T> Provider<T> proxyScope(Key<T> key, Provider<T> scopedProvider, SessionStoreScope currentScope) { if (key.getTypeLiteral().getRawType().isAssignableFrom(EventBus.class)) { return () -> { final BeanStore relatedStore = currentScope.getStore(); EventBus protectedEventBus = relatedStore.get((Key<EventBus>) key); if (protectedEventBus == null) { protectedEventBus = new ResettableEventBus((EventBus) scopedProvider.get()); relatedStore.put(key, protectedEventBus); } return (T) protectedEventBus; }; } throw new IllegalArgumentException("Can only proxy EventBus objects, do not know what to do with [" + key + "]"); } }
@Test public void testDoesNotDispatchToRemovedHandler() { // GIVEN ResettableEventBus eventBus = new ResettableEventBus(new SimpleEventBus()); InvocationCountingTestEventHandler handler = new InvocationCountingTestEventHandler(); HandlerRegistration registration = eventBus.addHandler(TestEvent.class, handler); registration.removeHandler(); // WHEN eventBus.fireEvent(new TestEvent()); // THEN assertEquals(0, handler.getInvocationCount()); }
ResettableEventBus eventBus = new ResettableEventBus(new SimpleEventBus());