Add: Event interface and implement it in DisconnectEvent, update EventBus to only allow Event type
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
package ch.unibas.dmi.dbis.cs108.casono.server.network;
|
||||
|
||||
public record DisconnectEvent(SessionId sessionId) {}
|
||||
public record DisconnectEvent(SessionId sessionId) implements Event {}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
package ch.unibas.dmi.dbis.cs108.casono.server.network;
|
||||
|
||||
interface Event {}
|
||||
@@ -9,12 +9,12 @@ import java.util.function.Consumer;
|
||||
public class EventBus {
|
||||
private final Map<Class<?>, List<Consumer<Object>>> handlers = new ConcurrentHashMap<>();
|
||||
|
||||
public <T> void subscribe(Class<T> eventType, Consumer<T> handler) {
|
||||
public <T extends Event> void subscribe(Class<T> eventType, Consumer<T> handler) {
|
||||
handlers.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>())
|
||||
.add((Consumer<Object>) handler);
|
||||
}
|
||||
|
||||
public <T> void publish(T event) {
|
||||
public <T extends Event> void publish(T event) {
|
||||
List<Consumer<Object>> subscribers = handlers.get(event.getClass());
|
||||
if (subscribers != null) {
|
||||
subscribers.forEach(h -> h.accept(event));
|
||||
|
||||
Reference in New Issue
Block a user