In CDI 2.0 one can fire an event asynchronously by calling Event.fireAsync()
and then listen to this event by with a @ObservesAsync
annotated listener.
Why do we need both Event.firesAsync()
and @ObservesAsync
?
- Couldn't CDI 2.0 process asynchronously an event fired by
Event.fire()
and caught with@ObservesAsync
? - Or reversely, why couldn't CDI 2.0 asynchronously process an event fired by
Event.fireAsync()
and caught with@Observes
?
A very good question indeed, here is a bit of insight.
CDI EG (expert group) decided against mixing those two for several reasons:
Event.fireAsync()
gives you aCompletionStage
to which you can chain next steps withexceptionally()
orthenApply()
etc. This naturally fits into asynchronous programming model.Event.fire()
only gives youvoid
, to which you cannot react at all - not good for asyncCompletionStage
, you can easily react to that.Event.fire()
(if it were for async as well)RequestScoped
needs to be re-activated, by Weld, in the async observer thread)Other advantages of the current model I can think of:
fireAsync()
allows you to fire event with additional optionsNotificationOptions
which allow you to specify an executor for your notificationsfireAsync()
you have matching@ObservesAsync