Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/main/java/cam72cam/mod/event/Event.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,46 @@
public class Event<T> {
private final Set<Runnable> pre = new LinkedHashSet<>();
private final Set<T> callbacks = new LinkedHashSet<>();
private final Set<T> flushableCallbacks = new LinkedHashSet<>();
private final Set<Runnable> post = new LinkedHashSet<>();

public void pre(Runnable callback) {
pre.add(callback);
}

//If this event is fired only 1 time per game launch or should be handled indifferently
public void subscribe(T callback) {
callbacks.add(callback);
}

//If this event is fired multiple times per game launch and should be handled separately
public void subscribeFlushable(T callback) {
subscribe(callback);
flushableCallbacks.add(callback);
}

public void post(Runnable callback) {
post.add(callback);
}

void execute(Consumer<T> handler) {
pre.forEach(Runnable::run);
callbacks.forEach(handler);
callbacks.removeAll(flushableCallbacks);

post.forEach(Runnable::run);
}

boolean executeCancellable(Function<T, Boolean> handler) {
pre.forEach(Runnable::run);
for (T callback : callbacks) {
for (T callback : new LinkedHashSet<>(callbacks)) {
if (!handler.apply(callback)) {
callbacks.removeAll(flushableCallbacks);
return false;
}
}
post.forEach(Runnable::run);
callbacks.removeAll(flushableCallbacks);
return true;
}
}