Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/async #1

Merged
merged 3 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public void onListenYourFavoriteEvent(YourFavoriteEvent event) {

## Future Plans 🛌

- [ ] Asynchronous events
- [x] Asynchronous events
- [x] Event cancellation
- [x] Event listener registration
- [x] Event listener deregistration
Expand Down
25 changes: 10 additions & 15 deletions src/main/java/at/jkvn/eventlib/EventLib.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,26 @@ public class EventLib {

@SneakyThrows
public static void call(Event event) {
if (isAutomatic()) {
invokeMethods(getMethods(), event, false);
return;
}

(new ArrayList<>(listeners)).forEach(listener -> {
invokeMethods(Arrays.stream(listener.getClass().getMethods()).toList(), event, false);
});
callEvent(event);
}

@SneakyThrows
public static void callAsync(Event event) {
executor.execute(() -> callEvent(event));
}

private static void callEvent(Event event) {
if (isAutomatic()) {
invokeMethods(getMethods(), event, true);
invokeMethods(getMethods(), event);
return;
}

(new ArrayList<>(listeners)).forEach(listener -> {
invokeMethods(Arrays.stream(listener.getClass().getMethods()).toList(), event, true);
invokeMethods(Arrays.stream(listener.getClass().getMethods()).toList(), event);
});
}

private static void invokeMethods(List<Method> methods, Event event, boolean async) {
private static void invokeMethods(List<Method> methods, Event event) {
methods.stream()
.filter(method -> method.getParameterCount() == 1
&& method.getParameterTypes()[0].isAssignableFrom(event.getClass()))
Expand All @@ -63,11 +60,9 @@ private static void invokeMethods(List<Method> methods, Event event, boolean asy
return priority != null ? priority.value().ordinal() : EventPriority.NORMAL.ordinal();
}))
.forEach(method -> {
if (async) {
executor.execute(() -> invokeSafely(method, event));
return;
if (!event.isCancelled()) {
invokeSafely(method, event);
}
invokeSafely(method, event);
});
}

Expand Down
Loading