Guava provides us with the event Bus Eventbus Library, which is the implementation of the event publish-subscribe pattern, which allows us to decouple the design of our modules and domain boundaries in domain-driven design (DDD) with the weak reference nature of events. Events
Guava the event passed in the publish-subscribe mode is an ordinary Pojo class.
Class Orderevent {
private String message;
Public orderevent (String message) {
this.message = message;
}
Public String GetMessage () {
return message;
}
}
Subscribe
After using guava, the publish-subscribe mode becomes simple, and if you need to subscribe to a certain type of message, simply add the @subscribe annotation to the specified method. The code is as follows:
Class helloeventlistener{
@Subscribe public
void Listen (Orderevent event) {
System.out.println (" Receive msg: "+event.getmessage ());
}
}
The subscription method name is not mandatory, this example uses the listen, you can use any method name. Registration & Release
Register the Subscriber (Subscriber) with the Eventbus.register (Object object) method to publish the event using the Eventbus.post (Object event) method.
The code is as follows:
Creates a new Eventbus with the given identifier.
Eventbus Eventbus = new Eventbus ("Ricky");
Register all subscriber
Eventbus.register (new Helloeventlistener ());
Publish Event
Eventbus.post (new orderevent ("Hello"));
Eventbus.post (New Orderevent ("World"));
Promotion Chapter
1. A subscriber can also subscribe to multiple events at the same time, guava will determine which subscription method to invoke Subscriber through the event type and the formal parameters of the subscribing method, as follows:
Class Multieventlistener {
@Subscribe public
void Listen (Orderevent event) {
System.out.println ("Receive Msg: "+event.getmessage ());
}
@Subscribe public
void Listen (String event) {
System.out.println ("Receive msg:" +event);
}
Eventbus post Orderevent type event, the Multieventlistener Listen (Orderevent event) method is called when the post string type event is The Multieventlistener Listen (String event) is called.
2. If multiple subscriber subscribe to the same event, each Subscriber will receive an event notification, and the order in which the event notifications are received is consistent with the order of registration, as shown in the following code:
Creates a new Eventbus with the given identifier.
Eventbus Eventbus = new Eventbus ("Ricky");
Register all subscriber
Eventbus.register (new Helloeventlistener ());
Eventbus.register (New Multieventlistener ());
Publish Event
Eventbus.post (new orderevent ("Hello"));
Eventbus.post (New Orderevent ("World"));
Eventbus.post ("Haha");
Both Helloeventlistener and Multieventlistener subscribe to the Orderevent event, so they will receive a orderevent event notification. But Helloeventlistener will be the first to receive Orderevent event notification, followed by Helloeventlistener.