|
| 1 | +package life.qbic.domain.concepts; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * <b>Local Domain Event Dispatcher</b> |
| 8 | + * <p> |
| 9 | + * Dispatches domain events to registered {@link DomainEventSubscriber}. |
| 10 | + * <p> |
| 11 | + * In contrast to the {@link DomainEventDispatcher} class, this class offers a |
| 12 | + * {@link LocalDomainEventDispatcher#reset()} method to clear all potentially existing subscribes. |
| 13 | + * This enables the domain event dispatcher to be used in an isolated local domain interaction |
| 14 | + * scope, e.g. from within an application service, when you want to ensure a successful committed |
| 15 | + * transaction first but still want to make use of broadcasting domain events within your domain. |
| 16 | + * <p> |
| 17 | + * <strong>Disclaimer</strong> |
| 18 | + * <p>The implementation runs in the main application thread and is blocking. Depending on the |
| 19 | + * number of registered subscriber and their implementation, expect the dispatching of events to |
| 20 | + * block your main app.</p> |
| 21 | + * |
| 22 | + * @since 1.0.0 |
| 23 | + */ |
| 24 | +public class LocalDomainEventDispatcher { |
| 25 | + |
| 26 | + private static final ThreadLocal<List<DomainEventSubscriber<?>>> subscribers = ThreadLocal.withInitial( |
| 27 | + ArrayList::new); |
| 28 | + private static LocalDomainEventDispatcher INSTANCE; |
| 29 | + |
| 30 | + private LocalDomainEventDispatcher() { |
| 31 | + subscribers.set(new ArrayList<>()); |
| 32 | + } |
| 33 | + |
| 34 | + public static LocalDomainEventDispatcher instance() { |
| 35 | + if (INSTANCE == null) { |
| 36 | + INSTANCE = new LocalDomainEventDispatcher(); |
| 37 | + } |
| 38 | + return INSTANCE; |
| 39 | + } |
| 40 | + |
| 41 | + public <T extends DomainEvent> void subscribe(DomainEventSubscriber<T> subscriber) { |
| 42 | + var currentSubscribers = subscribers.get(); |
| 43 | + currentSubscribers.add(subscriber); |
| 44 | + subscribers.set(currentSubscribers); |
| 45 | + } |
| 46 | + |
| 47 | + public <T extends DomainEvent> void dispatch(T domainEvent) { |
| 48 | + subscribers.get().stream() |
| 49 | + .filter(subscriber -> subscriber.subscribedToEventType() == domainEvent.getClass()) |
| 50 | + .map(subscriber -> (DomainEventSubscriber<T>) subscriber) |
| 51 | + .forEach(subscriber -> subscriber.handleEvent(domainEvent)); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Removes all existing {@link DomainEventSubscriber}s of the dispatcher instance. |
| 56 | + * |
| 57 | + * @since 1.0.0 |
| 58 | + */ |
| 59 | + public void reset() { |
| 60 | + subscribers.remove(); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments