Using CDI 2.0 event and @observesAsync with a class and qualifier, it is possible to further refine which observers get notified via some kind of run time assigned property? That is to say, is it possible to specify which single observer gets triggered by using a unique identifier, or do all the observers have to look at the event and decide if it was for them?
Typical way to achieve your desired behaviour is to use qualifiers.
... is it possible to specify which single observer gets triggered by using a unique identifier ...
It is - use a unique qualifier which does not trigger any other observer. It does not work in the way that all the observers "look" at the event. CDI will filter this and only deliver it to the subset which is relevant to the event you fired.
Below is a rather detailed example of how event and observers work with qualifiers; please note that this can be done with both, synchronous and asynchronous events. Same as injection points, events can have qualifiers. Say you have the following events:
@Inject Event<MyPayload> basic;
@Inject @Awesome Event<MyPayload> awesome;
@Inject @Tricky Event<MyPayload> tricky;
@Inject @Awesome @Tricky Event<MyPayload> combined;
For simplicity sake, let us stick to firing these event simply by <eventName>.fireAsync(new MyPayload())
.
Now for the observers - those can have qualifiers as well. The set of qualifiers determines which events they will be notified of. So here is a bunch of observers:
public void asyncObserver1(@ObservesAsync MyPayload event)
public void asyncObserver2(@ObservesAsync @Awesome MyPayload event)
public void asyncObserver3(@ObservesAsync @Tricky MyPayload event)
public void asyncObserver4(@ObservesAsync @Awesome @Tricky MyPayload event)
Now to which observer will be notified of which event. The general rule is - An observer method will be notified if the set of observer qualifiers is a subset of the fired event's qualifiers or an empty set
Assuming you fired the events above:
asyncObserver1
will be notified of all those events because its set of qualifiers is an empty oneasyncObserver2
will be notified of awesome
and combined
eventsasyncObserver3
will be notified of tricky
and combined
eventsasyncObserver4
will only be notified of the combined
eventLast but not least, I suggest you glimpse at the CDI documentation to get a deeper insight.