1. Overview
1.概述
Guava library provides the EventBus which allows publish-subscribe communication between components. In this tutorial, we will look at how to use some of the features of the EventBus.
Guava库提供了EventBus,允许组件之间进行发布-订阅通信。在本教程中,我们将了解如何使用EventBus的一些功能。
2. Setup
2.设置
To start we add the Google Guava library dependency in the pom.xml:
首先,我们在pom.xml中添加Google Guava库的依赖性:。
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
3. Using the EventBus
3.使用 EventBus
Let’s start by using a simple example.
让我们先用一个简单的例子来说明。
3.1. Setup
3.1.设置
We start by looking at the EventBus object. It can register listeners and post events. Using it is as simple as instantiating the class:
我们先看一下EventBus对象。它可以注册监听器和发布事件。使用它就像实例化该类一样简单。
EventBus eventBus = new EventBus();
Guava library gives you the freedom of using the EventBus in any way that best suits your development needs.
Guava库让你可以以任何最适合你的开发需求的方式自由使用EventBus。
3.2. Creating Listeners
3.2.创建监听器
public class EventListener {
private static int eventsHandled;
@Subscribe
public void stringEvent(String event) {
eventsHandled++;
}
}
3.3. Registering Listeners
3.3.注册监听器
EventListener listener = new EventListener();
eventBus.register(listener);
3.4. Unregistering Listeners
3.4.取消注册监听器
If for any reason we want to unregister a class from the EventBus, that can also be easily done:
如果出于任何原因,我们想从EventBus中取消一个类的注册,这也可以很容易做到。
eventBus.unregister(listener);
3.5. Posting Events
3.5.发布事件
@Test
public void givenStringEvent_whenEventHandled_thenSuccess() {
eventBus.post("String Event");
assertEquals(1, listener.getEventsHandled());
}
3.6. Posting Custom Events
3.6.发布自定义事件
public class CustomEvent {
private String action;
// standard getters/setters and constructors
}
Adding a handler method in the EventListener class for that event:
在EventListener类中为该事件添加一个处理方法。
@Subscribe
public void someCustomEvent(CustomEvent customEvent) {
eventsHandled++;
}
We can now post our custom event:
我们现在可以发布我们的自定义事件。
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() {
CustomEvent customEvent = new CustomEvent("Custom Event");
eventBus.post(customEvent);
assertEquals(1, listener.getEventsHandled());
}
3.7. Handling an Unsubscribed Event
3.7.处理一个未订阅的事件
We are provided with a DeadEvent class that allows us to handle any events that have no listeners. We can add a method to handle the DeadEvent class:
我们获得了一个DeadEvent类,它允许我们处理任何没有监听器的事件。我们可以添加一个方法来处理DeadEvent类。
@Subscribe
public void handleDeadEvent(DeadEvent deadEvent) {
eventsHandled++;
}
4. Conclusion
4.结论
In this tutorial, we used a simple example as a guide on how to use the Guava EventBus.
在本教程中,我们用一个简单的例子来指导如何使用Guava EventBus。
You can find the complete source code and all code snippets for this article over on GitHub.
你可以在GitHub上找到本文的完整源代码和所有代码片段。