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
27 changes: 24 additions & 3 deletions src/main/java/cam72cam/mod/event/Event.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,26 @@
import java.util.function.Function;

public class Event<T> {
private final Set<Runnable> pre = new LinkedHashSet<>();
private final Set<T> callbacks = new LinkedHashSet<>();
private final Set<Runnable> post = new LinkedHashSet<>();
final Set<Runnable> pre = new LinkedHashSet<>();
final Set<T> callbacks = new LinkedHashSet<>();
final Set<Runnable> post = new LinkedHashSet<>();

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

public void subscribe(T callback) {
callbacks.add(callback);
}

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

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

post.forEach(Runnable::run);
}

Expand All @@ -35,4 +39,21 @@ boolean executeCancellable(Function<T, Boolean> handler) {
post.forEach(Runnable::run);
return true;
}

/**
* For those events fired multiple times and should be handled respectively
*/
static class TransientEvent<T> extends Event<T> {
@Override
void execute(Consumer<T> handler) {
super.execute(handler);
callbacks.clear();
}

boolean executeCancellable(Function<T, Boolean> handler) {
boolean result = super.executeCancellable(handler);
callbacks.clear();
return result;
}
}
}