Reputation: 1351
I am trying to use guava for subscribing to EventBus. Trying to look at the site doc but unable to see any example where it shows how to do it.
Anyone tried this before??
private final EventBus eventBus = new EventBus();
eventBus.post(eventId); // where eventId is a string.
This is being in one of the jars. Now I need to subscribe to this eventbus and check if there are any new eventId's posted. How can I do that?
Any help is appreciated.
Thanks!!
Upvotes: 4
Views: 12964
Reputation: 1
Here is a simple demo.
public class EventBusDemo{
public static void main(String[] args) {
handleTransaction();
}
public static void handleTransaction() {
CatSubscriber catSubscriber = new CatSubscriber();
PandaSubscriber pandaSubscriber = new PandaSubscriber();
DogSubscriber dogSubscriber = new DogSubscriber();
EventBus eventBus = new EventBus();
Animal cat = new Cat();
Animal dog = new Dog();
Animal panda = new Panda();
eventBus.register(pandaSubscriber);
eventBus.register(catSubscriber);
eventBus.register(dogSubscriber);
eventBus.post(cat);
eventBus.post(dog);
eventBus.post(panda);
}
}
interface Animal {
void run();
}
class Cat implements Animal {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
System.out.println(Cat.class.getSimpleName() + " run");
}
}
class CatSubscriber {
@Subscribe
public void catRun(Animal animal) {
animal.run();
}
}
class Dog implements Animal {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
System.out.println(Dog.class.getSimpleName() + " run");
}
}
class DogSubscriber {
@Subscribe
public void dogRun(Animal animal) {
animal.run();
}
}
class Panda implements Animal {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
System.out.println(Panda.class.getSimpleName() + " run");
}
}
class PandaSubscriber {
@Subscribe
public void pandaRun(Animal animal) {
animal.run();
}
}
Upvotes: 0
Reputation: 110054
You would need some object with a method annotated @Subscribe
that takes a parameter of type String
(since you're posting a String
as an event to it... note that some more specific event type is probably preferable). You then need to pass that object to the EventBus.register(Object) method. Example:
public class Foo {
@Subscribe
public void handleEvent(String eventId) {
// do something
}
}
Foo foo = ...
eventBus.register(foo);
eventBus.post(eventId);
Upvotes: 9