Skip to content

Commit

Permalink
Added async events
Browse files Browse the repository at this point in the history
  • Loading branch information
swnck committed Feb 28, 2024
1 parent 77f3880 commit a915112
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/main/java/at/jkvn/eventlib/EventLib.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,43 @@
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Getter
public class EventLib {
@Getter
private static Configuration configuration;
@Getter
private static final List<Listener> listeners = new ArrayList<>();
@Getter
private static final ExecutorService executor = Executors.newCachedThreadPool();

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

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

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

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

private static void invokeMethods(List<Method> methods, Event event) {
private static void invokeMethods(List<Method> methods, Event event, boolean async) {
methods.stream()
.filter(method -> method.getParameterCount() == 1
&& method.getParameterTypes()[0].isAssignableFrom(event.getClass()))
Expand All @@ -47,6 +63,10 @@ private static void invokeMethods(List<Method> methods, Event event) {
return priority != null ? priority.value().ordinal() : EventPriority.NORMAL.ordinal();
}))
.forEach(method -> {
if (async) {
executor.execute(() -> invokeSafely(method, event));
return;
}
invokeSafely(method, event);
});
}
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/TestProject.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ public void call() {
assertTrue(dummyEvent.wasCalled());
}

@Test
public void callAsync() {
DummyEvent dummyEvent = new DummyEvent();

EventLib.callAsync(dummyEvent);

assertTrue(dummyEvent.wasCalled());
}

@EventHandler
public void onDummyEvent(DummyEvent event) {
event.call();
Expand Down

0 comments on commit a915112

Please sign in to comment.