Last active
May 12, 2023 18:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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