feat(EventBus): add event priority
This commit is contained in:
@@ -13,14 +13,18 @@ public class EventBus {
|
||||
|
||||
public void register(Object host) {
|
||||
for (Method method : host.getClass().getDeclaredMethods()) {
|
||||
if (method.isAnnotationPresent(Subscribe.class)) {
|
||||
Class<?>[] params = method.getParameterTypes();
|
||||
if (params.length == 1) {
|
||||
Class<?> eventType = params[0];
|
||||
Subscribe subscribe = method.getAnnotation(Subscribe.class);
|
||||
if (subscribe == null) continue;
|
||||
|
||||
listeners.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>())
|
||||
.add(Listener.of(host, method));
|
||||
}
|
||||
Class<?>[] params = method.getParameterTypes();
|
||||
if (params.length == 1) {
|
||||
Class<?> eventType = params[0];
|
||||
|
||||
Listener listener = Listener.of(host, subscribe.priority(), method);
|
||||
List<Listener> registry = listeners.computeIfAbsent(eventType,
|
||||
k -> new CopyOnWriteArrayList<>());
|
||||
|
||||
register(registry, listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,4 +44,13 @@ public class EventBus {
|
||||
listener.invoke(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void register(List<Listener> registry, Listener target) {
|
||||
int i = 0;
|
||||
for (Listener listener : registry) {
|
||||
i++;
|
||||
if (target.priority() > listener.priority()) break;
|
||||
}
|
||||
registry.add(i, target);
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import java.lang.invoke.*;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record Listener(Object host, Consumer<Object> consumer) {
|
||||
public static Listener of(Object host, Method method) {
|
||||
return new Listener(host, buildLambdaMetafactory(host, method));
|
||||
public record Listener(Object host, int priority, Consumer<Object> consumer) {
|
||||
public static Listener of(Object host, int priority, Method method) {
|
||||
return new Listener(host, priority, buildLambdaMetafactory(host, method));
|
||||
}
|
||||
|
||||
public void invoke(Object event) {
|
||||
|
||||
@@ -8,5 +8,6 @@ import java.lang.annotation.Target;
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Subscribe {
|
||||
int priority() default 0;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user