blob: 1ed04c56af3ebada490acaf9c942ed5f8cd337f9 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package coffee.liz.ecs.events;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
/**
* Minimal observable contract for event emission.
*
* @param <E>
* emitted event type
*/
public class EventBus<E> {
protected final Set<Consumer<E>> subscriptions = new CopyOnWriteArraySet<>();
/**
* Register a hook to receive future events.
*
* @param hook
* callback to invoke for each emitted event
* @return subscribed hook.
*/
public Consumer<E> subscribe(final Consumer<E> hook) {
subscriptions.add(hook);
return hook;
}
/**
* Remove a previously registered hook.
*
* @param hook callback to remove
*/
public void unsubscribe(final Consumer<E> hook) {
subscriptions.remove(hook);
}
/**
* Publish an event to all currently subscribed hooks.
*
* @param event
* event to publish
*/
public void emit(final E event) {
subscriptions.forEach(s -> s.accept(event));
}
}
|