type=page
status=published
title=Using Events in CDI Applications
next=cdi-adv006.html
prev=cdi-adv004.html
~~~~~~
= Using Events in CDI Applications


[[GKHIC]]

[[using-events-in-cdi-applications]]
Using Events in CDI Applications
--------------------------------

Events allow beans to communicate without any compile-time dependency.
One bean can define an event, another bean can fire the event, and yet
another bean can handle the event. In addition, events can be fired asynchronously. The beans can be in separate packages
and even in separate tiers of the application.

[[GKHHY]]

[[defining-events]]
Defining Events
~~~~~~~~~~~~~~~

An event consists of the following:

* The event object, a Java object
* Zero or more qualifier types, the event qualifiers

For example, in the `billpayment` example described in
link:cdi-adv-examples005.html#GKHPA[The billpayment Example: Using Events
and Interceptors], a `PaymentEvent` bean defines an event using three
properties, which have setter and getter methods:

[source,oac_no_warn]
----
    public String paymentType;
    public BigDecimal value;
    public Date datetime;

    public PaymentEvent() {
    }
----

The example also defines qualifiers that distinguish between two kinds
of `PaymentEvent`. Every event also has the default qualifier `@Any`.

[[GKHNF]]

[[using-observer-methods-to-handle-events]]
Using Observer Methods to Handle Events
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

An event handler uses an observer method to consume events.

Each observer method takes as a parameter an event of a specific event
type that is annotated with the `@Observes` annotation and with any
qualifiers for that event type. The observer method is notified of an
event if the event object matches the event type and if all the
qualifiers of the event match the observer method event qualifiers.

The observer method can take other parameters in addition to the event
parameter. The additional parameters are injection points and can
declare qualifiers.

The event handler for the `billpayment` example, `PaymentHandler`,
defines two observer methods, one for each type of `PaymentEvent`:

[source,oac_no_warn]
----
public void creditPayment(@Observes @Credit PaymentEvent event) {
    ...
}

public void debitPayment(@Observes @Debit PaymentEvent event) {
    ...
}
----

[[conditional-and-transactional-observer-methods]]
Conditional and Transactional Observer Methods
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Observer methods can also be conditional or transactional:

* A conditional observer method is notified of an event only if an
instance of the bean that defines the observer method already exists in
the current context. To declare a conditional observer method, specify
`notifyObserver=IF_EXISTS` as an argument to `@Observes`:
+
[source,oac_no_warn]
----
@Observes(notifyObserver=IF_EXISTS)
----
+
To obtain the default unconditional behavior, you can specify
`@Observes(notifyObserver=ALWAYS)`.
* A transactional observer method is notified of an event during the
before-completion or after-completion phase of the transaction in which
the event was fired. You can also specify that the notification is to
occur only after the transaction has completed successfully or
unsuccessfully. To specify a transactional observer method, use any of
the following arguments to `@Observes`:
+
[source,oac_no_warn]
----
@Observes(during=BEFORE_COMPLETION)

@Observes(during=AFTER_COMPLETION)

@Observes(during=AFTER_SUCCESS)

@Observes(during=AFTER_FAILURE)
----
+
To obtain the default nontransactional behavior, specify
`@Observes(during=IN_PROGRESS)`.
+
An observer method that is called before completion of a transaction may
call the `setRollbackOnly` method on the transaction instance to force a
transaction rollback.

Observer methods may throw exceptions. If a transactional observer
method throws an exception, the exception is caught by the container. If
the observer method is nontransactional, the exception terminates
processing of the event, and no other observer methods for the event are
called.

[[observer-method-ordering]]
Observer Method Ordering
^^^^^^^^^^^^^^^^^^^^^^^^

Before a certain observer event notification is generated, the container determines the order in which observer methods for that event are invoked. Observer method order is established through the declaration of the `@Priority` annotation on an event parameter of an observer method, as in the following example:

[source,oac_no_warn]
----
void afterLogin(@Observes @Priority(javax.interceptor.Interceptor.Priority.APPLICATION) LoggedInEvent event) { ... }
----

Note the following:

* If the `@Priority` annotation is not specified, the default value is `javax.interceptor.Interceptor.Priority.APPLICATION + 500`.
* If two or more observer methods are assigned the same priority, the order in which they are invoked is undefined and is therefore unpredictable.

[[GKHIH]]

[[firing-events]]
Firing Events
~~~~~~~~~~~~~

Beans fire events by implementing an instance of the `javax.enterprise.event.Event` interface. Events can be fired synchronously or asynchronously.

[[firing-events-synchronously]]
Firing Events Synchronously
^^^^^^^^^^^^^^^^^^^^^^^^^^^

To activate an event synchronously, call the `javax.enterprise.event.Event.fire`
method. This method fires an event and notifies any observer methods.

In the `billpayment` example, a managed bean called `PaymentBean` fires
the appropriate event by using information it receives from the user
interface. There are actually four event beans, two for the event object
and two for the payload. The managed bean injects the two event beans.
The `pay` method uses a `switch` statement to choose which event to
fire, using `new` to create the payload.

[source,oac_no_warn]
----
    @Inject
    @Credit
    Event<PaymentEvent> creditEvent;

    @Inject
    @Debit
    Event<PaymentEvent> debitEvent;

    private static final int DEBIT = 1;
    private static final int CREDIT = 2;
    private int paymentOption = DEBIT;
    ...

    @Logged
    public String pay() {
        ...
        switch (paymentOption) {
            case DEBIT:
                PaymentEvent debitPayload = new PaymentEvent();
                // populate payload ...
                debitEvent.fire(debitPayload);
                break;
            case CREDIT:
                PaymentEvent creditPayload = new PaymentEvent();
                // populate payload ...
                creditEvent.fire(creditPayload);
                break;
            default:
                logger.severe("Invalid payment option!");
        }
        ...
    }
----

The argument to the `fire` method is a `PaymentEvent` that contains the
payload. The fired event is then consumed by the observer methods.

[[firing-events-asynchronously]]
Firing Events Asynchronously
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To activate an event asynchronously, call the `javax.enterprise.event.Event.fireAsync` method. This method calls all resolved asynchronous observers in one or more different threads.

[source,oac_no_warn]
----
@Inject Event<LoggedInEvent> loggedInEvent;

public void login() {
    ...
    loggedInEvent.fireAsync( new LoggedInEvent(user) );
}
----

The invocation of the `fireAsync()` method returns immediately.

When events are fired asynchronously, observer methods are notified asynchronously. Consequently, observer method ordering cannot be guaranteed, because observer method invocation and the firing of asynchronous events occur on separate threads.
