Skip to content

Instantly share code, notes, and snippets.

@scompt
Created May 3, 2012 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scompt/2584272 to your computer and use it in GitHub Desktop.
Save scompt/2584272 to your computer and use it in GitHub Desktop.
An EventBus that persists the most recent event sent.
package com.google.common.eventbus;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.Multimap;
import com.google.common.collect.MutableClassToInstanceMap;
import roboguice.util.Ln;
import java.util.concurrent.Executor;
/**
* An {@link EventBus} that persists the most recent event sent.
*
* This class has to be in this package because the EventBus isn't really meant for extension. It could potentially
* stop working with the next Guava release. See
* http://groups.google.com/group/guava-discuss/browse_thread/thread/80f97e66728fe4dc/cdf758d64f1cf50b
*/
public class PersistingAsyncEventBus extends AsyncEventBus {
private final HandlerFindingStrategy myFinder = new AnnotatedHandlerFinder();
private final ClassToInstanceMap<Object> sentEvents = MutableClassToInstanceMap.create();
public PersistingAsyncEventBus(final String identifier, final Executor executor) {
super(identifier, executor);
}
@Override
public void post(final Object event) {
super.post(event);
sentEvents.put(event.getClass(), event);
}
@Override
public void register(final Object object) {
super.register(object);
final Multimap<Class<?>,EventHandler> allHandlers = myFinder.findAllHandlers(object);
for (Class<?> aClass : allHandlers.keySet()) {
final Object event = sentEvents.getInstance(aClass);
if(event != null) {
for (EventHandler eventHandler : allHandlers.get(aClass)) {
Ln.i("Enqueing cached event %s to %s", event, eventHandler);
enqueueEvent(event, eventHandler);
}
}
}
dispatchQueuedEvents();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment