Skip to content

Instantly share code, notes, and snippets.

@falkoschumann
Last active May 12, 2023 18:16
Show Gist options
  • Save falkoschumann/9fcc743006bef02368de3a6a93fce463 to your computer and use it in GitHub Desktop.
Save falkoschumann/9fcc743006bef02368de3a6a93fce463 to your computer and use it in GitHub Desktop.
This is a utility class that can be used by beans that emit events.
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
public class EventEmitter<T> {
private final List<Consumer<T>> listeners = new CopyOnWriteArrayList<>();
public EventEmitter() {
// public ctor
}
public void addListener(Consumer<T> listener) {
Objects.requireNonNull(listener, "listener");
listeners.add(listener);
}
public void removeListener(Consumer<T> listener) {
Objects.requireNonNull(listener, "listener");
listeners.remove(listener);
}
public void emit(T value) {
listeners.forEach(l -> l.accept(value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment