Tim
Tim

Reputation: 4274

CDI2.0 Why can't the BeanManager fire Async Events?

I am testing the new CDI2.0 pre-release and I was expecting the BeanManager to be able to fire events asynchronously.

In CDI 1.2 I was doing this:

@Inject
BeanManager beanManager;

public void fireEvents() {
        for (int i = 0; i < 10; i++) {
            beanManager.fireEvent(new LightEvent("Light Event " + i));
            beanManager.fireEvent(new HeavyEvent("Heavy Event " + i));
        }
    } 

As I wanted to test async events, I saw that the BeanManager does not have a fireAsync() method. Instead, I have to fire the events the other way:

@Inject
private Event<LightEvent> lightEvent;

@Inject
private Event<HeavyEvent> heavyEvent;

public void fireAsyncEvents() {
    for (int i = 0; i < 10; i++) {
        lightEvent.fireAsync(new LightEvent("light " + i));
        heavyEvent.fireAsync(new HeavyEvent("heavy " + i));
    }
}

Now this works fine, but I have to define the events first. Are there any plans to add a fireAsync() method to the Beanmanager ?

Upvotes: 3

Views: 536

Answers (1)

Siliarus
Siliarus

Reputation: 6753

Because a decision was taken not to bloat BeanManager (BM) that much. To elaborate further, there were people asking for fireAsync as well as people asking for option to fire event directly from BM with selected qualifiers or type, or type and qualifiers. All of those are valid requirements but adding all this onto BM would bloat this "uber" entry point even more.

Therefore, a decision was made to instead create BeanManager#getEvent() from which you get into an Event interface directly. From there you can do select(..) based on desired qualifiers/types (or leave it default) and you then fire (for sync events) or fireAsync (for async).

To support my statements above, you can read more in related CDI issue or check the pull request directly.

So what you are after is already there and probably looks like this:

@Inject
BeanManager bm;

public void myMethod() {
  // default one
  bm.getEvent().fireAsync(new MyPayload());
  // with selections of subtype and qualifiers
  bm.getEvent().select(MyType.class, MyQualifier.class).fireAsync(new MyPayload());
}

Upvotes: 4

Related Questions