package envoy.event; import java.util.*; import java.util.function.Consumer; /** * This class handles events by allowing event handlers to register themselves * and then be notified about certain events dispatched by the event bus.
*
* The event bus is a singleton and can be used across the entire application to * guarantee the propagation of events.
*
* Project: envoy-common
* File: EventBus.java
* Created: 04.12.2019
* * @author Kai S. K. Engelbart * @since Envoy v0.2-alpha */ public final class EventBus { /** * Contains all event handler instances registered at this event bus as values * mapped to by their supported event classes. */ private Map>, List>>> handlers = new HashMap<>(); /** * The singleton instance of this event bus that is used across the * entire application. */ private static EventBus eventBus = new EventBus(); /** * This constructor is not accessible from outside this class because a * singleton instance of it is provided by the {@link EventBus#getInstance()} * method. */ private EventBus() {} /** * @return the singleton instance of the event bus * @since Envoy v0.2-alpha */ public static EventBus getInstance() { return eventBus; } /** * Registers an event handler to be notified when an * event of a certain type is dispatched. * * @param the type of event values to notify the handler about * @param eventClass the class which the event handler is subscribing to * @param handler the event handler to register * @since Envoy v0.2-alpha */ public > void register(Class eventClass, Consumer handler) { if (!handlers.containsKey(eventClass)) handlers.put(eventClass, new ArrayList<>()); handlers.get(eventClass).add((Consumer>) handler); } /** * Dispatches an event to every event handler subscribed to it. * * @param event the {@link Event} to dispatch * @since Envoy v0.2-alpha */ public void dispatch(Event event) { handlers.keySet() .stream() .filter(event.getClass()::equals) .map(handlers::get) .flatMap(List::stream) .forEach(h -> h.accept(event)); } /** * @return a map of all event handler instances currently registered at this * event bus with the event classes they are subscribed to as keys * @since Envoy v0.2-alpha */ public Map>, List>>> getHandlers() { return handlers; } }