I am having a hard time to understand the benefits of using the Event Bus concept in GWT .
I have gone through many examples showing how to use it. I get how it is made but i dont see why it does help .
I take example :
Button button = new Button("click");
button.addListener(new ButtonListenerAdapter(){
#Override
public void onClick(Button button, EventObject e) {
doSomething() ;// must replace it with fireEvent later :(
}
});
In order to add the event bus ability to the code above we have to introduce more code:
1)create an event class that extends Event (implement 2 methods)
2) create interface for event handler where dosomething() will be abstract
3) Implement the interface
4) The class in which the event happens has to implement HasHandler interface, intreoduce HandlerManager instance ,implement fireEvent , registers the event and fires the event.
Now my problem is that, if i have 50 UI events, i cant see the benefit of duplicating the above 4 steps where it should be. If I dont do it what is really the problem i am going to face.
Edit :
Is the fact that Events & Events handlers if they are separated in classes makes the EventBus pattern interesting?
AddContactEvent.java
AddContactEventHandler.java
RemoveContactEvent.java
RemoveContactEventHandler.java
No event bus
Example: You can buy apples from the farm directly.
Button maintains the collection of listeners. Button is aware about all listeners and needs to notify them in the loop. Button is directly coupled with the handlers.
Event bus
Example: You buy apples from a store and store buys apples from the farm. The store is a broker between you and the farm. You are not aware about the farm. The farm is not aware about you.
Event bus is broker between the event producer and event consumer. Event producer is aware about event bus but not all event consumers.
Button is not aware about the listeners. It's aware about EventBus only.
Handlers are not aware about the Button. They are aware about the bus.
Summary:
Applications without plugins may be implemented without event bus.
Applications with plugin support should be implemented with the event bus as it's not known before hand how many plugins are connected to the event producer.
Related
I looked for this online, but couldn't find an adequate explanation to what it exactly does. What I saw was a Java Interface and it was passed as a parameter in another class as a "Listener". People added various listeners to a list and called them all through a single method.
I'm not sure why I would use it. Can someone care to explain?
This is my original help post where someone told me to use listeners.
Link
In the code example that you linked the KillMonsterEventListener
public interface KillMonsterEventListener {
void onKillMonster ();
}
provides a way for users of your API to tell you something like this:
Here is a piece of code. When a monster is killed, call it back. I will decide what to do.
This is a way for me to plug in my code at a specific point in your execution stream (specifically, at the point when a monster is killed). I can do something like this:
yourClass.addKillMonsterEventListener(
new KillMonsterEventListener() {
public onKillMonster() {
System.out.println("A good monster is a dead monster!");
}
}
);
Somewhere else I could add another listener:
yourClass.addKillMonsterEventListener(
new KillMonsterEventListener() {
public onKillMonster() {
monsterCount--;
}
}
);
When your code goes through the list of listeners on killing a monster, i.e.
for (KillMonsterEventListener listener : listeners) {
listener.onKillMonster()
}
both my code snippets (i.e. the monsterCount-- and the printout) get executed. The nice thing about it is that your code is completely decoupled from mine: it has no idea what I am printing, what variable I am decrementing, and so on.
Listener is a common form of implementing the observer design patter in Java. This technique is also referred to as the callback, which is a term coming from the world of procedural languages.
Observers register themselves by the observable, which in turn calls back the observers whenever some event occurs or when they should be notified about something.
Many framework libraries play the role of the observable, e.g.:
You register yourself (i.e., your implementation of the listener interface) as a listener of incoming messages in a messaging middleware.
You register yourself as a listener of some changes made by the user in the operating system.
You register yourself as a listener of GUI events, such as a button was click on.
Example in Java code:
Part 1 - The observable entity
import java.util.LinkedList;
import java.util.List;
public class Observable {
private List<Observer> observers;
public Observable() {
observers = new LinkedList<>();
}
public void addObsever(Observer observer) {
observers.add(observer);
}
private void notifyObservers(String whatHappened) {
for (Observer observer : observers) {
observer.onSomethingHappened(whatHappened);
}
}
public void doSomeStuff() {
// ...
// Do some business logic here.
// ...
// Now we want to notify all the listeners about something.
notifyObservers("We found it!");
// ...
// Do some business logic here
// ...
}
}
Part 2 - The observer/listener interface
public interface Observer {
void onSomethingHappened(String whatHappened);
}
Part 3 - Basic implementation of the observer/listener interface
public class MyObserver implements Observer {
#Override
public void onSomethingHappened(String whatHappened) {
System.out.println(whatHappened);
}
}
Part 4 - Putting it all together
public class Main {
public static void main(String[] args) {
// Create the observable.
Observable myObservable = new Observable();
// Create the observers (aka listeners).
Observer myObserverA = new MyObserver();
Observer myObserverB = new MyObserver();
// Register the observers (aka listeners).
myObservable.addObsever(myObserverA);
myObservable.addObsever(myObserverB);
myObservable.doSomeStuff();
}
}
And the result on standard output will be:
We found it!
We found it!
This is part of a programming paradigm called event-driven programming. Objects send messages to other objects on certain occasions, for example when they change. This is used often in GUI programming. Each GUI widget is implemented by a class. When you want to handle e.g. mouse clicks from the user, you add a listener (also called event handler) to GUI widget. When the user clicks on the widget, the widget sends the event to the registered listener(s) so that the application can respond to the mouse click. This seperates the framework (the GUI widget class) and the application code. (In some GUI frameworks, such as Swing, you can add an arbitrary number of listeners to an object; in others, you can specify only one.)
Also in other areas event-driven programming is useful. You might want to observe an object (see Observer pattern). For example, a collection which supports this, might send an event if its contents change. If you need to perform some processing if this occurs, you can add yourself as a listener to this class. The alternative would be to call the post-processing every time you add an item to the collection, but this error-prone.
Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener.
Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.
You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur.
Here is the blog post for Servlet Listener
http://array151.blogspot.in/2016/12/servlet-listener.html
Use a listener to let other code inform you of "conditions"/"events". For instance a "mouse listener" could be called if the mouse would have been moved/clicked/dragged. It depends on your application why it provides for listeners.
Listeners do some work when an event occurs. They are called as "Event Listeners".
Events like click, hover etc..
For Example, we have ActionListener interface in Java. It calls actionPerformed() method when an event occurs.
You can refer http://java.about.com/od/a/g/Actionlistener.htm for more info.
Listeners are used for notify about state changes. You can think about Listeners in most of time as Observers, so every time something interesting happen your listener will be called.
You can read more about patterns in Java on following websites:
http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial
http://www.developer.com/java/implementing-behavioral-patterns-in-java.html
I have a java class buried deep in an SDK that performs an action and returns a boolean. It has no knowledge of the application's main activity, but I need the main activity to receive that boolean value.
I've seen a lot of questions regarding callbacks, broadcasts, and listeners but they all seem to have knowledge of the activity. My pojo does have an activityContext but I don't know how to get the value back to the application's main activity.
I'm already using an AsyncTask in my pojo and I'm trying to figure out how to send the boolean in the onPostExecute method in a way that the application's main activity can receive it.
Does anybody know how to do this?
I'd suggest using a message bus or observable/observer pattern.
Square has Otto a nice little open-source library that implements a message bus.
Observer pattern is well described at wikipedia for example.
Either way what you will have to do is essentially start listening to either your POJO if you make it Observable, or subscribe for bus events in onResume() (or onStart()) and stop listening in onPause() in your activity.
BUS
I like bus more because of it's loose coupling and the fact that you can send any arbitrary POJOs to the bus and only listen to one specific type for example.
so you post a message this:
bus.post(new SomethingICareAbout("I really really do"));
and elsewhere in your codebase (in your case in the activity):
#Subscribe
public void onSomethingIcareAbout(SomethingICareAbout thingsAndStuff) {
// TODO: React to the event somehow. Use what you received.
}
#Subscribe
public void onSomethingElseIcareAbout(SomethingElseICareAbout otherThings) {
// TODO: React to the event somehow. Use what you received.
}
The above is intentionally simplified, you still need to create the bus and subscribe to it, but you will find that in the docs :P
Also it uses annotations and is really lightweight (codewise).
Observer / Observable
Observer/Observable on the other had is part of Java, so it's built in. But it is tightly coupled, your activity will have to implement Observer, your POJO will implement Observable and you willl have to implement update() method in your Activity, this one will get all the updates no matter what you send by the Observable.
I hope this makes sense a bit :)
I need to to make for school a simple "strategy game simulator". To do this I need to make an Event Dispatcher (event loop) that will send the event to the registered parties. For example, I have resources on the map. One event is "resource at location 1 depleted". And one "player" is interested on that event.
How would I create the dispatcher (and register one player for one particular event). Also, how does the dispatcher check for the event? Does it simply do something like if(resourceLocation1.getNoResource()==0) trigerEvent(); or is there some other, more elegant way.
I worked with event listeners (mostly in ActionScrip3) but never made a custom event and a custom event dispatcher. Any help is appreciated, including some links to some tutorials or sample codes.
If I am not clear what I am searching for please let me know and I will try to explain it better
Thanks.
Your EventDispatcher does not need to check every possible condition and notify all possible listeners. Just notify listeners registered for a certain type of event.
Register Player to be notified depending on the game event
eventDispatcher.register(player, Events.RESOURCE_DEPLETION_EVENT);
Then your Resource would supply an event when resources reached 0
class Resource {
public void deplete(int amount) {
this.amount -= amount;
if (this.amount <= 0)
eventDispatcher.notify(this, Events.RESOURCE_DEPLETION_EVENT);
}
}
Otherwise you are going to end up with a massive logic-containing event loop that eats up performance and will be difficult to debug.
Java has a built-in thread-safe Observer pattern you can use.
To write your own you would have Player implement a ResourceDepeletionListener interface and add it to an array of listeners in your Resource class. When the resources reach zero they call resourcesDepleted() on all ResourceDepeletionListener objects.
What about implementing an observer pattern?
For instance, you can have a ResourceObserver, which registers a particular Resource as an observable. From there, you can have Player objects register as observers to your ResourceObserver. A map object will hold all the resources. In your event loop, you will have something like:
...
Map.updateResources();
...
So for instance, when you call updateResources, all the map resources will check if they have been depleted. If a resource has been depeleted, it will notify it's ResourceObserver, which will in turn notify all registered players for that resource.
I'm designing a stand-alone, multi-threaded application in Java.
I'm trying to choose the best event-handling solution for his project.
I have 1-3 threads generating events (e.g comm thread completes file upload), while other threads might want to be registered for notification on this event.
I want the event-generating and event listening to be as uncoupled as possible.
What do you suggest?
Use an event bus.
An event bus can be thought of as a
replacement for the observer pattern,
where in the observer pattern, each
component is observing an observable
directly. In the event bus pattern,
each component simply subscribes to
the event bus and waits for its event
notification methods to be invoked
when interesting events have occurred.
In this way, an event bus can be
thought of like the observer pattern
with an extra layer of decoupling.
Here's a nice presentation about using an event bus ins GWT. It should give you a good idea about the benefits (and it's quite funny, too).
EDIT
The first link is mainly given as an example. It's really not that hard implementing something similar on your own which fits your needs.
I would use ExecutorServices to manage your thread pools. This way when you have a listener to an event, you can ensure the event is added to the right service either using a Proxy, or hande coded. e.g.
public void onEventOne(final Type parameter) {
executorService.submit(new Runnable() {
public void run() {
wrappedListener.onEventOne(parameter);
}
}
}
You can pass this listener wrapper as and be sure the event will be processed using the desired thread pool.
Using a Proxy allows you to avoid this type of boiler plate code. ;)
Do you really need a solution where each thread can register as a listener for each type of event? If so, use an event bus type solution (or a centralized observable with typed events).
If you don't need this flexibility a manager-worker setup could suffice, where the manager gets notified of events (like: "I'm finished with my job") and can fire up workers as needed.
Usage of an event bus is definitely the right choise. There are various solutions out there. You can also check out MBassador https://github.com/bennidi/mbassador.
It is annotation driven, very light-weight and uses weak references (thus easy to integrate in environments where objects lifecycle management is done by a framework like spring or guice or somethign). It provides an object filtering mechanism and synchronous or asynchronous dispatch/message handling. And it's very fast!
Google Guava has an event bus as well but it uses strong references which can be a pain if you do not have full control over your object lifecycle (e.g. spring environment)
EDIT: I created a performance and feature comparison for a selection of available event bus implementations including Guava, MBassador and some more. The results are quite interesting. Check it out here
http://codeblock.engio.net/?p=37
use command design pattern to decoupling
In general terms of java, there are listeners & handlers for events.
I mean I use them unknowingly, just whichever is available in the API.
My question is, in what case do we use listeners and in what case do we use handlers for events?
What's the difference between them? Characteristics??
I've searched for reasons and I couldn't find a proper explanation for Java.
There's no formally defined difference between listeners and handlers. Some people would probably argue that they are interchangeable. To me however, they have slightly different meaning.
A listener is an object that subscribes for events from a source. Cf. the observer pattern. Usually you can have many listeners subscribing for each type of event, and they are added through addXyzListener methods.
Example: The MouseListener in the Java API.
A handler is an object that is responsible for handling certain events. A typical scenario would be to provide a handler for a specific event/task as an argument to a constructor, or set the handler through a setXyzHandler method. In other words, you usually have one handler for each type of event.
Example: The MemoryHandler in the Java API.
The most basic difference is the association
Listener is associated with Event Source (Ex: key board)
Handler is associated with an Event (Ex: keydown)
Generally speaking, there will only one central Handler Manager which manages all the events, while in case of Listener each Entity which wants to listen, will have to manage their own Collection of listeners
This is the way I see it:
A listener watches for an event to be fired. For example, a KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue and so on.
The handler is responsible for dealing with the event. Normally, listeners and handlers go hand-in-hand. For example, the KeyListener tells the ExitHandler that "the letter Q was pressed" and the handler performs logic such as cleaning up resources and exiting the application gracefully. Similary a ButtonClickListener would tell the same ExitHandler that the "Exit button was clicked". So, in this case you have two different events, two different listeners but a single handler.
A listener is an object that is notified when an event occurs, and it has 2 major requirements-
1-it must have been registered with one or more sources to receive notifications about specific types of event
2-it must implements methods to receive and process these notifications.
Handler is responsible for dealing with events.
To my mind, the most important difference is fact that we use listeners per event's source, in contrary to handler, which is per event type.
A listener, listens for events which are data value objects which describe an event. When the event occurred and the order of events is often important. Pressing key '0' followed by '1' is different to '1' and '0'.
A handler, handles a complex object e.g. a new Socket connection. The handler might process the object for any length of time. The time of object creation and order is not so important. A connection from client0 or client1 can happen in any order.
I think the difference is subtle because a concrete Listener is an event-handler too or at least has a method that can be considered an event-handler.
That is, a concrete Listener handles or manages the reaction to the event after receiving an event object(from the event-source) with all the usefull informations about the event just occurred(on the event-source).
As this Listener has to implement an xxxListener interface that forces him to implement at least one method that is in turn executed by the event-source object when the event occurs, so the Listener itself can be considered an handler and more precisely, the method of the Listener interface implemented by the Listener object can be considered the real event-handler.
So i view the event-handler as just the code that is executed in reaction to an event.
This is different from a Listener object that is an element of a more abstract concept such as an Observer design pattern.
This is my personal view of the subject.
They're conceptually the same thing - an object that performs some action in response to a UI event. Generally, in Swing, these objects are called "handlers" at the look-and-feel level (for handling low-level widget events), and "listeners" at the more abstract UI level (where you'll be implementing your application logic).
EventHandler is introduced in the JavaFX for all the UI controls. Whereas the Listener is borrowed for Observables, such as properties.
The EventHandler is a way to distinguish observable events and the ui events.
I've been trying to make sense of all the info and I'm lost. I've looked at Delphi (Pascal), C, C++, java... nothing is clear.So, after a month, this is the problem as I see it. I may be totally off track, so please tell me... politely, please.
One event sender, one catcher as long as Sender registers the catcher. I have 4 dialog boxes that need to be updated each time a file (whose handling code is in another module than the 4 dialog boxes) changes. I considered updating each the old-fashioned way, but then I looked at Delphi events and message handling. Let's see:
File F (The Sender) is finished reading and should notify Dialogs 1..4 of the fact that there is now data for them to display and the user to play with. What is best?
Try to register Dialogs 1..4 as listeners and have the Sender trigger an OnUpdatedDataEvent somehow?
Try sending a message across the system, hoping that Dialogs 1..4 will catch it?
Notice that the event keeps things coupled while messaging do not...and are a pain to debug.
And I do wonder how the File block of code will be able to register 4 listeners (the dialog boxes)?
What I am looking at is the possibility of cascade calling, meaning caller calls one listener, whom calls the next... until it reaches the end of the chain. I even wonder if that is even possible.
An example:
Say File F is a list of languages. Now, DialogBox 1 does something to the list (adds a new language for instance); that combo box updates the F file; this in turn triggers a DataUpdatedEvent. the 4 Dialog boxes contain, say, TComboBoxes that display the language list when they pop up. I want the 4 boxes to notice the change and update their own combo box contents with the freshly updated File... without having to worry about how the combo boxes know they need to refresh their contents. If it works as envisioned the Sender parameter will carry across and the dialog box that triggered the dataUpdateEvent will be bypassed since it will already be updated. After all an if sender=self then continue to next event handler should be easy to implement.
All that because I want to exercise my brain... to prevent Alzheimer's, not very successfully I might add.
Suppose you just landed at the airport by plane at a new destination. you have someone waiting for you at the gate OR someone who will drive the taxi and take you to your hotel
The person waiting is the listener (waiting for an event like you are arriving)
The person taking you to the hotel is the event handler (the action after you've arrived)
In JS, the listener waits for an event (e.g click) the handler does something father the "click" happened
It is semantics.
Listener is interface.
Adaptor is class that implements specific interface and provides empty implementation for its methods. This helps if you do not have to implement all methods of interface.
Handler implements several interfaces or delegates calls to several interfaces.