I would like to #Subscribe a method in a Runnable that is created by a ScheduledFuture, so that I can signal it from another thread whether to run. Because a ScheduledFuture creates the object at some future time, there is no scope for the #Subscribe listener to pick up my event. So, I'm wondering how long an event sits in the bus, waiting to picked up by a listener? Is the actual pub-sub synchronous wrt sending/receiving events or will they sit in a queue for some duration before timing out?
Thanks.
Guava's EventBus does not provide sticky events. Additionally, due to the design of EventBus, it's not as straightforward as it could be to extend it to implement such a sticky design, as a lot of the internals are package-private (e.g. the logic to discover which methods on a registered object are annotated with Subscribe and mapping them to the proper event type).
I do think there are some other libraries out there which do provide this, like GreenRobot's event bus (https://github.com/greenrobot/EventBus), but without introducing a new library you'll have to build it more or less from scratch.
An alternative that I've used is RxJava's Observables with a replay(1) operator, so that subscribing to the observable will always immediately invoke the subscription callback with the last item, but it's not a drop-in replacement.
I am new to Android and I have a kind of design question. So I understand that it is recommended to use Fragments. I also understand that an Activity "owns" a Fragment.
So my question is the following:
Assume we want to make a long running background call e.g. HTTP to a server.
The results should be displayed in the UI.
So what is the best/standard practice?
1) Should the object doing the long running calls be "owned" by the Activity and the results send back to the Activity and then from the Activity to the Fragment so that the UI is updated?
2) Or should the object doing the long running called be "owned" by the Fragment and the results are send back to the Fragment for the UI to be updated? So the Activity is completely unaware of this?
Neither, IMHO. The object doing the long running should be managed by a Service, where you are using WakeLock (and, if needed, WifiLock) while the long-running HTTP operation is running. An IntentService might be a good candidate, as you need a background thread anyway.
The service, in turn, can use some sort of in-process event bus (LocalBroadcastManager, greenrobot's EventBus, Square's Otto, etc.), to let the UI layer know about any significant events that occurred from that HTTP operation. Whether the activity or the fragment is the one to subscribe to the events on the bus depends on what needs to happen for the event. If a fragment's widgets need to be updated, the fragment would subscribe. If the mix of fragments change, or some other activity-level UI change is needed, the activity would subscribe.
All of this assumes that by "long running" you mean something taking over a second or so.
For the long running task it's recommended to implement a sticky Service that contains a thread for the ServerSocket listener. Next I'd recommend to process requests by dedicated Thread's which are managed by a thread pool (check for instance this example).
In order to display results in your activity there are several approaches possible:
send a local broadcast from your service or thread which gets processed by registered BroadcastReceiver's which are part of your UI component (either Fragment's or Activity's)
bind your Service to the Activity (which might contain further fragments) and propagate information to containing fragments. There are three ways to go.
Note: In this post it's being said it's better to bind to the Application
pass data via Intent or a SQLiteDatabase
What I like and prefer is using local BroadcastReceiver's but this is just my personal preference.
It depends on your requirements, what might be the best solution.
I'm using a variation of the design recommended by #CommonsWare. I have an ApiClient class that listens to the event bus for requests to invoke API methods asynchronously. Any parameters that are needed for the API call go into the bus request message.
The ApiClient uses Retrofit to make the async API call, and posts a 'result message' containing the result to the event bus on success, and an 'error message' if there's an error. Each API call has it's own triplet of bus messages - xxxRequest, xxxResponse, xxxError.
So, when an Activity or a Fragment (or other, non-ui class) wants to invoke the api, it registers to the bus for the xxxResponse and xxxError messages, and then posts an xxxRequest message to the bus.
The only potential down-sides are:
The ApiClient is a singleton, and is owned by the Application class, just so that it doesn't get garbage collected.
You wind up with a large number of Message classes - I deal with this by putting them into their own package.
In GWT I have class MyClass that registers some event handlers. There is an object (object1) of MyClass that, at a specific moment, I want to finalize and make its handlers stop listening, because after that I am going to create a different MyClass object (object2).
How can I do that? I already tried with object1 = null, but its handerls keep listening (at least for a while).
The handlers might still exist because the gc didn't get around destroying them.
If it is important that the listeners don't continue to exist then they need to be deregistered.
One way to do this is by deregistering the HandlerRegistration. For example a addClickHandler returns a HandlerRegistration which can be deregistered. When and how to do this depends on your GUI classes. You could put the deregistration in your finalize method but you will probably find that these methods are called very sporadically because of the gc and of course because this is not java but javaScript. So concider putting them in a detach or destroy method of your gui element onDetach or onUnload.
Let me first sketch the concrete situation I find myself in, although my question is actually more general. I'm writing a component containing several sliders and I have listeners listening for events from these sliders. When one of these sliders changes I want my component to send an event to its own listeners to notify them that its state has changed. I would however like to limit the number of events that are sent, i.e. if there are several events waiting when my component notifies its listeners, I would like to collapse all these events into a single event.
My question is whether there are standard techniques for this. If so, any example would be welcome, because I couldn't find any. (Maybe collapsing is not the correct terminology?)
I believe collapsing is the correct term. An example class from the Java Core libraries that implements such behavior is RepaintManager. I would check out it's source code to see how it collapses multiple repaint requests.
Before you do any such thing you should make sure that it is really necessary.
I guess you would need to access the EventQueue from your listener. When an event triggers the callback method, this method should first look in the queue to see if there are more recent events of the relevant type and, if so, process the most recent event only and then remove all events of that type from the queue.
Since the callbacks are always on the Swing (awt) event thread, you don't need to worry about concurrency.
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.