我正在尝试使用guava订阅EventBus。试图查看网站文档,但无法看到任何显示如何操作的示例。
之前有人试过吗?
private final EventBus eventBus = new EventBus();
eventBus.post(eventId); // where eventId is a string.
这是在其中一个罐子里。现在我需要订阅这个eventbus并检查是否有任何新的eventId已发布。我怎么能这样做?
感谢任何帮助。
谢谢!
答案 0 :(得分:8)
您需要一个带有注释@Subscribe
的方法的对象,该对象采用String
类型的参数(因为您将String
作为事件发布到它...请注意一些更具体的事件类型可能更可取)。然后,您需要将该对象传递给EventBus.register(Object)方法。例如:
public class Foo {
@Subscribe
public void handleEvent(String eventId) {
// do something
}
}
Foo foo = ...
eventBus.register(foo);
eventBus.post(eventId);
答案 1 :(得分:0)
这是一个简单的演示。
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);
}
}
界面动物{
void run();
}
类Cat实现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");
}
}
类CatSubscriber {
@Subscribe
public void catRun(Animal animal) {
animal.run();
}
}
类Dog实现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();
}
}
班熊猫实施动物{
@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");
}
}
类PandaSubscriber {
@Subscribe
public void pandaRun(Animal animal) {
animal.run();
}
}