This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/common/src/main/java/envoy/event/EventBus.java

83 lines
2.5 KiB
Java

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.<br>
* <br>
* The event bus is a singleton and can be used across the entire application to
* guarantee the propagation of events.<br>
* <br>
* Project: <strong>envoy-common</strong><br>
* File: <strong>EventBus.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
*
* @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<Class<? extends Event<?>>, List<Consumer<Event<?>>>> 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 <T> 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 <T extends Event<?>> void register(Class<T> eventClass, Consumer<T> handler) {
if (!handlers.containsKey(eventClass)) handlers.put(eventClass, new ArrayList<>());
handlers.get(eventClass).add((Consumer<Event<?>>) 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<Class<? extends Event<?>>, List<Consumer<Event<?>>>> getHandlers() { return handlers; }
}