Question

I created some instance of same classes with:

private Instance<MyObserver> myObserverFactory;

public MyObserver getNewInstance() {
  return myObserverFactory.get();
}

And my class:

// Dependent bean
public class MyObserver{
   public void observe(@Observes MyEvent myEvent) { /* do something */ }
}

Instead of having "manager bean" which keeps all MyObserver instances, I would like to communicate with them with events. But with Dependant scope, events are sent every time to a new instance of MyObserver... And with Dependant scope, I can't use:

@Observes(notifyObserver = Reception.IF_EXISTS)

So my question is: How to broadcast events between existing Dependant scoped beans? What scope can I use?

Thanks,

-Dush

Was it helpful?

Solution 2

I think Adrian Mitev is right: it's not possible to do that I as would like.

I'm using Guava Event Bus for this purpose (be able to ping existing instance of beans). And I'm routing CDI event to it with this class:

/**
 * Configure Guava Event Bus to get CDI event and broadcast them to it.
 */
@ApplicationScoped
public class GuavaEventBus {

  private static final Logger LOGGER = LoggerFactory.getLogger(GuavaEventBus.class);

  private static final EventBus eventBus = new EventBus();

  @Produces
  @ApplicationScoped
  private EventBus createGuavaEventBus() {
      return eventBus;
  }

  public void broadcastEveryEvent(@Observes Object event) {
      // There are a lot of bradcasted events, it may be a good solution to filter them.
      LOGGER.debug("Broadcast event: {}", event);
      eventBus.post(event);
  }

  /** Why not registring and unregistring by CDI event? ;) */ 
  public static void register(Object bean) {
      LOGGER.debug("Register bean: {}", bean);
      eventBus.register(bean);
  }

  public static void unregister(Object bean) {
      eventBus.unregister(bean);
  }

}

OTHER TIPS

Technically, one recourse is to make your observer method static, but that is probably pretty limiting if you expected to ping each bean during the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top