Skip to content

A3. Events

João Alves edited this page Apr 13, 2023 · 6 revisions

Introduction

This section explains how to publish, subscribe and process application events using the built-in EventDispatcher.

Modules

To use the implementations refered on this section you must include the following module(s):

  • pixel-commons (dependency of pixel-core)

Event Dispatcher

You can use the EventDispatcher to trigger events across decoupled components. An event can be published to a given [event name] and processed by multiple subscribers (as many as subscribed to the given event). This can be very useful to quickly propagate state changes throughout your game.

The EventDispatcher is available as an instanceable class:

EventDispatcher dispatcher = new EventDispatcher();

Alternatively, you can use the static default event dispatcher, as follows:

EventDispatcher dispatcher = EventDispatcher.getDefault();

Subscribing

To subscribe to an event (example of a "collision" event):

dispatcher.subscribe("collision", CollisionData.class, (data) -> {
  // ...
});

In the example above, the event name is "collision". Note that there is a class reference as the second argument, this binds "collision" events that are being published with a CollisionData value. In this scenario, the data value is automatically casted to the 2nd argument class type.

You can set the same event with different class references. The EventDispatcher filters by both (event name and class type).

Another example:

dispatcher.subscribe("collision", (data) -> {
  // ...
});

This is similar to the prior example but without the class reference filter. This subscription will catch any "collision" event regardless of the value type.

Publishing

To publish an event (again, "collision" is an example event name):

dispatcher.publish("collision", value);

Unsubscribing

To unsubscribe:

dispatcher.unsubscribe("collision", collisionListener);
Clone this wiki locally