package coffee.liz.ecs.events; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.function.Consumer; /** * Minimal observable contract for event emission. * * @param * emitted event type */ public class EventBus { protected final Set> subscriptions = new CopyOnWriteArraySet<>(); /** * Register a hook to receive future events. * * @param hook * callback to invoke for each emitted event * @return subscribed hook. */ public Consumer subscribe(final Consumer hook) { subscriptions.add(hook); return hook; } /** * Remove a previously registered hook. * * @param hook callback to remove */ public void unsubscribe(final Consumer hook) { subscriptions.remove(hook); } /** * Publish an event to all currently subscribed hooks. * * @param event * event to publish */ public void emit(final E event) { subscriptions.forEach(s -> s.accept(event)); } }