dev.robocode.tankroyale.botapi.internal.EventHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of robocode-tankroyale-bot-api Show documentation
Show all versions of robocode-tankroyale-bot-api Show documentation
Robocode Tank Royale Bot API for Java
The newest version!
package dev.robocode.tankroyale.botapi.internal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
/**
* Event handler which processes events in the order they have been added to the handler.
*/
final class EventHandler {
private final List subscriberEntries = new CopyOnWriteArrayList<>();
void subscribe(Consumer subscriber, int priority) {
subscriberEntries.add(new EntryWithPriority(subscriber, priority));
}
void subscribe(Consumer subscriber) {
subscribe(subscriber, 1);
}
void publish(T event) {
subscriberEntries.sort(new EntryWithPriorityComparator());
for (EntryWithPriority entry : new ArrayList<>(subscriberEntries)) {
entry.subscriber.accept(event);
}
}
class EntryWithPriority {
private final int priority; // Lower values means lower priority
private final Consumer subscriber;
EntryWithPriority(Consumer subscriber, int priority) {
this.subscriber = subscriber;
this.priority = priority;
}
}
class EntryWithPriorityComparator implements Comparator {
@Override
public int compare(EntryWithPriority e1, EntryWithPriority e2) {
return e2.priority - e1.priority;
}
}
}