Skip to content

Instantly share code, notes, and snippets.

@cattyngmd
Last active August 20, 2022 23:00
Show Gist options
  • Save cattyngmd/a8b689ef9c0a03f29f48ded9e2a5b0ea to your computer and use it in GitHub Desktop.
Save cattyngmd/a8b689ef9c0a03f29f48ded9e2a5b0ea to your computer and use it in GitHub Desktop.
java simple and lightweight eventbus
package wtf.cattyn.catbus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
public final class EventBusImpl {
private final Map<Object, List<Method>> listeners = new ConcurrentHashMap<>();
public void post(Object event) {
listeners.forEach((subscriber, methods) -> methods.stream().filter(method -> method.getParameterTypes()[0].equals(event.getClass())).forEach(method -> {
try {
method.invoke(subscriber, event);
} catch (Throwable e) {
e.printStackTrace();
}
}));
}
public void subscribe(Object o) {
listeners.putIfAbsent(o, Arrays.stream(o.getClass().getDeclaredMethods())
.filter(method -> method.isAnnotationPresent(Listener.class) && method.getParameterCount() == 1)
.collect(Collectors.toCollection(CopyOnWriteArrayList::new)));
}
public void unsubscribe(Object o) {
listeners.remove(o);
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Listener { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment