Event Bus
Motivation
Implementation
FIRST PATTERN
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
package io.github.chermehdi.bus; | |
/** | |
* interface describing a generic event, and it's associated meta data, it's this what's going to | |
* get sent in the bus to be dispatched to intrested Subscribers | |
* | |
* @author chermehdi | |
*/ | |
public interface Event<T> { | |
/** | |
* @returns the stored data associated with the event | |
*/ | |
T getData(); | |
} |
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
package io.github.chermehdi.bus; | |
import java.util.Set; | |
/** | |
* Description of a generic subscriber | |
* | |
* @author chermehdi | |
*/ | |
public interface Subscribable { | |
/** | |
* Consume the events dispatched by the bus, events passed as parameter are can only be of type | |
* declared by the supports() Set | |
*/ | |
void handle(Event<?> event); | |
/** | |
* describes the set of classes the subscribable object intends to handle | |
*/ | |
Set<Class<?>> supports(); | |
} |
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
package io.github.chermehdi.bus; | |
import java.util.List; | |
/** | |
* Description of the contract of a generic EventBus implementation, the library contains two main | |
* version, Sync and Async event bus implementations, if you want to provide your own implementation | |
* and stay compliant with the components of the library just implement this contract | |
* | |
* @author chermehdi | |
*/ | |
public interface EventBus { | |
/** | |
* registers a new subscribable to this EventBus instance | |
*/ | |
void register(Subscribable subscribable); | |
/** | |
* send the given event in this EventBus implementation to be consumed by interested subscribers | |
*/ | |
void dispatch(Event<?> event); | |
/** | |
* get the list of all the subscribers associated with this EventBus instance | |
*/ | |
List<Subscribable> getSubscribers(); | |
} |
The Subscribable declares a method to handle a given type of objects, and also what type of objects it supports by defining the supports method .
The Event Bus implementation holds a List of all the Subscribables and notify all of them each time a new event comes to the EventBus dispatch method .
SECOND PATTERN
This pattern is inspired from Guava’s implementation, the Event Bus implementation looks much simpler and easier to use. for every event consumer you can just annotate a given method with @Subscribe
and pass it an object of the type you want to consume (a single object/parameter) and you can register it as a message consumer by just calling
eventBus.register(objectContainingTheMethod);
eventBus.post(SomeObject)
and all the interested consumers will be notified .
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
package io.github.chermehdi.guavabus; | |
import java.lang.reflect.Method; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Vector; | |
import java.util.concurrent.ConcurrentHashMap; | |
import java.util.stream.Collectors; | |
/** | |
* Simple implementation demonstrating how a guava EventBus works generally, without all the noise | |
* of special cases handling, and special guava collections | |
* | |
* @author chermehdi | |
*/ | |
public class EventBus { | |
private Map<Class<?>, List<Invocation>> invocations; | |
private String name; | |
public EventBus(String name) { | |
this.name = name; | |
invocations = new ConcurrentHashMap<>(); | |
} | |
public void post(Object object) { | |
Class<?> clazz = object.getClass(); | |
if (invocations.containsKey(clazz)) { | |
invocations.get(clazz).forEach(invocation -> invocation.invoke(object)); | |
} | |
} | |
public void register(Object object) { | |
Class<?> currentClass = object.getClass(); | |
// we try to navigate the object tree back to object ot see if | |
// there is any annotated @Subscribe classes | |
while (currentClass != null) { | |
List<Method> subscribeMethods = findSubscriptionMethods(currentClass); | |
for (Method method : subscribeMethods) { | |
// we know for sure that it has only one parameter | |
Class<?> type = method.getParameterTypes()[0]; | |
if (invocations.containsKey(type)) { | |
invocations.get(type).add(new Invocation(method, object)); | |
} else { | |
List<Invocation> temp = new Vector<>(); | |
temp.add(new Invocation(method, object)); | |
invocations.put(type, temp); | |
} | |
} | |
currentClass = currentClass.getSuperclass(); | |
} | |
} | |
private List<Method> findSubscriptionMethods(Class<?> type) { | |
List<Method> subscribeMethods = Arrays.stream(type.getDeclaredMethods()) | |
.filter(method -> method.isAnnotationPresent(Subscribe.class)) | |
.collect(Collectors.toList()); | |
checkSubscriberMethods(subscribeMethods); | |
return subscribeMethods; | |
} | |
private void checkSubscriberMethods(List<Method> subscribeMethods) { | |
boolean hasMoreThanOneParameter = subscribeMethods.stream() | |
.anyMatch(method -> method.getParameterCount() != 1); | |
if (hasMoreThanOneParameter) { | |
throw new IllegalArgumentException( | |
"Method annotated with @Susbscribe has more than one parameter"); | |
} | |
} | |
public Map<Class<?>, List<Invocation>> getInvocations() { | |
return invocations; | |
} | |
public String getName() { | |
return name; | |
} | |
} |
You can see that opting for this solution requires less work from your part, nothing prevents you from naming your handler methods intention-revealing names rather than a general handle . and you can define all your consumers on the same class you just need to pass an different event type for each method .
Conclusion
Implementing an Event Bus pattern can be beneficial for your code base as it help loose coupling your classes and promotes a publish-subscribe pattern , it also help components interact without being aware of each other . which implementation to follow is a matter of taste and requirements .
Great post!
Just a simple note about the second implementation.
It would be nice to add an identifier to the event on the annotation (something like @Subscribe(“db-user-insert”))
And only invoke the Invocation on methods whose id is equal to the event bus name.
+
I don’t see why you use Vector instead of ArrayList. If you are worried about concurrency issues, you still have some. (Post an event, thread get interrupted, register an object, continue posting events).
LikeLike
i didn’t want to add explicit locking, Vector was just simple to use, i could’ve made the post and register methods synchronized, but it’s the same solution if you do it at the Vector level .
LikeLike