Skip to content

Commit

Permalink
Merge pull request #1 from swnck/feature/async
Browse files Browse the repository at this point in the history
Feature/async
  • Loading branch information
swnck authored Mar 7, 2024
2 parents a915112 + 192c16f commit 83b98df
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 16 deletions.
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

0 comments on commit 83b98df

Please sign in to comment.