Last active
August 9, 2023 18:52
-
-
Save falkoschumann/896c2368b50228353929ed6e0e153d68 to your computer and use it in GitHub Desktop.
Simple message bus for in process communication.
This file contains hidden or 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 MessageBus { | |
private static final MessageBus DEFAULT = new MessageBus(); | |
private final List<Consumer<Object>> consumers = new CopyOnWriteArrayList<>(); | |
public MessageBus() { | |
// public ctor | |
} | |
static MessageBus getDefault() { | |
return DEFAULT; | |
} | |
public void addConsumer(Consumer<Object> consumer) { | |
Objects.requireNonNull(consumer, "The consumer cannot be null."); | |
consumers.add(consumer); | |
} | |
public void removeConsumer(Consumer<Object> consumer) { | |
Objects.requireNonNull(consumer, "The consumer cannot be null."); | |
consumers.remove(consumer); | |
} | |
public void publish(Object value) { | |
consumers.forEach(l -> l.accept(value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment