Reputation: 1889
I am looking at using the Guava EventBus in my application to distribute data (Double
s for example) from one or more data creators through to data consumer.
I know in my consumer class, I need to annotate my data handler with @Subscribe
. Is there a way in which to make this subscription conditional? So for example
@Subscribe {newValue > 0.0} public void valueUpdated(Double newValue)
I could add the check within my valueUpdated
method, but is there a way to stop the EventBus
from dispatching values that my Subscriber is not interested in?
Is there a product similar to EventBus that may provide this sort of function?
Upvotes: 3
Views: 797
Reputation: 751
you could achieve this using with Guava EventBus using your own Dispatcher implementation where you dispatch an event of type MyEvent only if it is interesting i.e. its newValue is greater than 0.
package com.google.common.eventbus;
import com.google.common.util.concurrent.MoreExecutors;
import lombok.Data;
import java.util.Iterator;
import static com.google.common.base.Preconditions.checkNotNull;
public class MyDispatcher extends Dispatcher {
private static final MyDispatcher INSTANCE = new MyDispatcher();
@Override
void dispatch(Object event, Iterator<Subscriber> subscribers) {
checkNotNull(event);
if (event instanceof MyEvent) {
Double newValue = ((MyEvent) event).getNewValue();
if (null != newValue && newValue > 0.0d) { //dispatch events only if newValue > 0.0d
while (subscribers.hasNext()) {
subscribers.next().dispatchEvent(event);
}
}
} else {
while (subscribers.hasNext()) {
subscribers.next().dispatchEvent(event);
}
}
}
@Data
public static class MyEvent {
private Object sender;
private Double newValue;
}
public static class MyEventBus extends EventBus {
public MyEventBus() {
super("myEventBys", MoreExecutors.newDirectExecutorService(), MyDispatcher.INSTANCE,
LoggingHandler.INSTANCE);
}
}
}
Upvotes: 0
Reputation: 32004
Spring Expression Language (SpEL) may help.
Plus: after checking the EventBus, I think it's type-based dispatch, no way to apply condition-based dispatch. If you insist on using Expression Language, you could put it in subscriber as Louis comment. But Expression Language is designed for flexibility rather than speed.
Upvotes: 1