I'm managing the History in my project via Places.
What I do is this:
implement PlaceRequestHandler on top level (for example AppController),
register it -> eventBus.addHandler(PlaceRequestEvent.getType(), this);
implement method "onPlaceRequest" ,where i do project navigation.
I'm using GWT presenter and every presenter in my project overrides the onPlaceRequest method.
Why do I need this, when every request is handled from the top level "onPlaceRequest" method?
I will give an example:
public class AppController implements Presenter, PlaceRequestHandler
...........
public void bind()
{
eventBus.addHandler(PlaceRequestEvent.getType(), this);
...
}
public void onPlaceRequest(PlaceRequestEvent event)
{
// here is the project navigation tree
}
and let's take one presenter
public class SomePresenter extends Presenter<SomePresenter.Display>
{
... here some methods are overriden and
#Override
protected void onPlaceRequest(PlaceRequest request)
{
// what should I do here?
}
}
What is the idea, and how I'm supposed to use it?
Instead of making all of your presenters extend PlaceRequestHandler and managing those events yourself, you can attach a PlaceHistoryHandler and a PlaceController to your event bus. Together, they manage the browser's history and your places for you. When you ask your PlaceController to goTo() a different place, it will stop your current activity and use a mapping of places to activities (your presenters) to choose which one to start next.
To use this technique, you need to have your presenters extend AbstractActivity. Try following through Google's tutorial about it in GWT's documentation called GWT Development with Activities and Places.
Related
Our company has been developing Android application using MVP pattern a while. With MVP, we put all business logic inside the presenter and the Activity/Fragment then just responsible for view update when receiving event callback from presenter.
Now, we decided to try MVVM using Android Databinding. It seems that with MVVM, we can put all the business logic in the ViewModel (just like Presenter in MVP) and also notify the view(s) of any changes to data model, all in one object.
But then, this raise question in our mind, what should we left to be handle by the Activity/Fragment? Since we adopted the MVP pattern to avoid fat-activity/fragment. We don't want to have slim-activity/fragment and then fat-viewmodel.
What we think we can left to be handle by Activity/Fragment so far
Request/Check permission
Access Context
Access Resources
Every correction, comment or suggestion are welcome since I'm fairly new to MVVM, even if it seems to be similar to MVP.
Thank you.
A bit more question
Is it possible and good practice to combine MVVM with listener (like MVP)? For example
public class MainActivityViewModel extends BaseObservable {
MainActivityViewModelListener listener;
User user;
public void setMainActivityViewModelListener(MainActivityViewModelListener listener) {
this.listener = listener;
}
public void refreshUser(View v) {
// some user update via Internet
notifyPropertyChanged(BR.userAlias);
if (listener != null) {
listener.onUserRefreshed(user);
}
}
#Bindable
public void getUserAlias() {
return user.getAlias();
}
}
public interface MainActivityViewModelListener {
void onUserRefreshed(User user);
}
public class MainActivity implements MainActivityViewModelListener {
MainActivityBinding binding;
#Override
public void onCreate(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(R.layout.main_activity);
MainActivityViewModel viewModel = new MainActivityViewModel();
viewModel.setMainActivityViewModelListener(this);
binding.setMainActivityViewModel(viewModel);
}
#Override
public void onUserRefreshed(User user) {
// do some update
}
}
Yes you can have all business logic in your ViewModel, Here are some links which i personaly follows to learn MVVM
Approaching Android with MVVM
https://github.com/ivacf/archi
MVVM on Android: What You Need to Know
You can mention all your listeners in ViewModel as well as data which your model will consist.
ViewModel alters some content and notifies the binding framework that content has changed.
Model - Data model containing business and validation logic
View -
Defines the structure, layout and appearance of a view on screen
ViewModel - Acts a link between the View and Model, dealing with any
view logic
reference
You should not set the Listener in the Activity.
Logic should be written as far as possible into the ViewModel.
I wrote a demo of MVVM(Databinding) a while ago.
Hope it helps you:
https://github.com/adgvcxz/Dribbble-MVVM
The answer for your question that can you use interface listeners inside mvvm just like you do in mvp? is yes but pattern is little different
the code u mentioned
public interface MainActivityViewModelListener {
void onUserRefreshed(User user);
is ok for mvp type designs but for mvvm you should use proper observer register and unregister pattern including notifying observers.
in mvp we directly call an interface function but observer pattern in mvvm is quite different from these simple interfaces. Observer pattern involve Subject registration with client class.
if you want to how exactly Mvvm works see here
https://github.com/saksham24/Android-Firebase-Mvp-Mvc-Mvvm-chat
this is a simple application with same functionality but written in three different formats to give a clear idea of difference between mvp mvvm and mvc
I am somewhat new to the OSGi world. And some concepts still elude me.
I'm trying to create a graphical OSGi application using Swing, Equinox and Declarative Services. The goal is to ease the creation of plugins and extensions for the application.
I have stumbled with a design problem and, since I am doing this from the ground up, I want to use all the best practices I can.
I do have a bundle that contains the API and only exposes interfaces to be implemented as services.
public class SomeClass {
}
public interface Manager<T> {
void add(T obj);
void update(T obj);
void remove(T obj);
}
public interface SomeClassManager extends Manager<SomeClass> {
}
public interface Listener<T> {
void added(T obj);
void updated(T obj);
void removed(T obj);
}
public interface SomeClassListener extends Listener<SomeClass> {
}
Let's say I have a bundle (Core) that provides a service that is a manager of certain types of objects (It basically contains an internal List and adds, removes and updates it).
public class SomeClassCoreManager implements SomeClassManager {
private ArrayList<SomeClass> list = new ArrayList<SomeClass>();
private ArrayList<SomeListener> listeners = new ArrayList<SomeListener>();
protected void bindListener(SomeListener listener) {
listeners.add(listener);
}
protected void undindListener(SomeListener listener) {
listeners.remove(listener);
}
public void add(SomeClass obj) {
// Adds the object to the list
// Fires all the listeners with "added(obj)"
}
public void update(SomeClass obj) {
// Updates the object in the list.
// Fires all the listeners with "updated(obj)"
}
public void remove(SomeClass obj) {
// Removes the object from the list.
// Fires all the listeners with "removed(obj)"
}
}
I also have a second bundle (UI) that takes care of the main UI. It should not "care" for the object managing itself, but should be notified when an object is added, removed or changed in order to update a JTree. For that purpose I used a Whiteboard pattern: The UI bundle implements a service that is used by the Core bundle to fire object change events.
public class MainWindow extends JFrame {
private JTree tree = new JTree();
private SomeClassManager manager;
protected void activate() {
// Adds the tree and sets its model and creates the rest of the UI.
}
protected void bindManager(SomeClassManager manager) {
this.manager = manager;
}
protected unbindManager(SomeClassManager manager) {
this.manager = null;
}
}
public class SomeClassUIListener implements SomeClassListener {
public void added(SomeClass obj) {
// Should add the object to the JTree.
}
public void updated(SomeClass obj) {
// Should update the existing object in the JTree.
}
public void removed(SomeClass obj) {
// Should remove the existing object from the JTree.
}
}
My problem here is the following:
The MainWindow is a DS component. I am using its activator to initiate the whole UI. The instance creation is handled by OSGi.
In order to get the updates from the manager, I am exposing the SomeClassUIListener as a Declarative Service. Its instance is also handled by OSGi.
How should I access the instance of the JTree model from the SomeClassUIListener?
I have come up with several options but I am not sure which to use:
Option 1:
Use some kind of internal DI system for the UI bundle (like Guice or Pico) and put it in a class with a static method to get it and use it all over the bundle.
This approach seems to be frowned upon by some.
Option 2:
Inject a reference to the MainWindow (by turning it into a service) in the SomeClassUIListener through OSGi and go from there. Is this possible or advisable? Seems to me that it is the simpler solution. But, on the other hand, wouldn't this clutter the bundle with component config files as the UI got more and more complex?
Option 3:
Create a separate bundle only for listeners and use OSGi to update the MainWindow. This seems to me a bit extreme, as I would have to create an enormous amount of bundles as the UI complexity grows.
Option 4:
Use the MainWindow class to implement the Listener. But, the more services in the main UI bundle, the bigger the MainWindow class would be. I think this would not be a good option.
I cannot think of more options. Is any of the above the way to go? Or is there another option?
Thank you in advance.
Edit:
Just to clarify as Peter Kriens had some doubts about this question.
My goal here is to decouple the user interface from the Manager. By Manager I mean a kind of repository in which I store a certain type of objects (For instance, if you consider the Oracle's JTree tutorial at http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html, the manager would contain instances of Books).
The Manager may be used by any other bundle but, according to my current plan, it would notify any listener registered in it. The listener may be the main UI bundle but may also be any other bundle that chooses to listen for updates.
I am not sure I completely grasp your proposal, and it feels like you are on your way to create a whole load of infrastructure. In OSGi this is generally not necessary, so why not start small and simple.
Your basic model is a manager and an extension. This is the domain model and I would try to flow things around here:
#Component(immediate)
public class ManagerImpl { // No API == immediate
List<Extension> extensions = new CopyOnWriteArrayList<Extension>();
JFrame frame = new JFrame();
#Reference(cardinality=MULTIPLE)
void addExtension( Extension e ) {
addComponent(frame, e.getName(), e.getComponent());
extensions.add(e);
}
void removeExtension( Extension e) {
if ( extensions.remove(e) ) {
removeComponent(frame, e.getName());
}
}
#Component
public class MyFirstExtension implements Extension {
public String getName() { return "My First Extension";}
public Component getComponent() { return new MyFirstExtensionComponent(this); }
}
Isn't this what you're looking for? Be very careful not to create all kinds of listeners, in general you find the events already in the OSGi registry.
Some option here would be to pass the tree model instance as the argument in the listeners methods.
public void added(JTree tree, SomeClass obj)
This way listeners manager would be responsible only for listeners logic, not for the tree state.
Another nice option would be to create a separated TreeProviderService, responsible for holding and serving singleton JTree instance for the application. In such case you would consume TreeProviderService directly from the listeners.
I propose to simply also use DS for the UI creation and wiring. If you use the annotations Peter mentioned you will not clutter your bundles with component descriptors in XML form.
So your listener is a #Component and you inject the UI elements it needs to update into it.
Btw. what you plan to do sounds a bit like databinding to me so you should also investigate what these offer already.
See: Swing data binding frameworks
Btw. you may also want to look for more advanced frameworks than swing. For example some time ago I did a small tutorial for vaadin: https://github.com/cschneider/Karaf-Tutorial/tree/master/vaadin
It already has a databinding for java beans. So this made it really easy for me to code the UI. The full UI is just this little class: https://github.com/cschneider/Karaf-Tutorial/blob/master/vaadin/tasklist-ui-vaadin/src/main/java/net/lr/tutorial/karaf/vaadin/ExampleApplication.java
In the old version I still needed a bridge to run vaadin in OSGi but version 7 should be quite OSGi ready.
The section on GWT testing describes how to verify output of Presenter in Display object, but does not explain how to do the other way around. In other words, I want to check whether Presenter will make a correct request to RPC Service when a user clicks button in Display.
How can I simulate button click in Display? Firing GWT events is not straightforward, as they have protected constructors. Is there a way to do it simply, without subclassing ClickEvent class?
#Before
protected void setUp() {
mockRpcService = mock(NegotiationServiceAsync.class);
eventBus = new HandlerManager(null);
mockDisplay = mock(NegotiationPresenter.Display.class);
negotiationPresenter = new NegotiationPresenter(mockRpcService,
eventBus, mockDisplay);
}
#Test
private void testSth() {
when(mockDisplay.getSuppliersEmails()).thenReturn("address#domain.com");
when(mockDisplay.getTaskDescription()).thenReturn("This is the task to do");
// This does not work
mockDisplay.getSubmitButton().fireEvent(new ClickEvent());
verify(mockRpcService).startTask(any(NegotiationRequest.class), any(AsyncCallback.class));
}
When you use MVP you normally test methods in the presenter injecting a mocked implementation of the view, so in your test the display does nothing, just offers stub methods to the presenter.
In the other hand, your real display implementation should delegate all actions to the presenter.
The way to test the behavior of your presenter when a user clicks on the submit button is calling the method in the presenter, something like this:
#Test
private void testSth() {
when(mockDisplay.getSuppliersEmails()).thenReturn("address#domain.com");
when(mockDisplay.getTaskDescription()).thenReturn("This is the task to do");
negotiationPresenter.onSubmit();
verify(mockRpcService).startTask(any(NegotiationRequest.class),
any(AsyncCallback.class));
}
A very different case is if you wanted to test your code using GWTTestCase so as you could use real view implementations, but in this case your tests would last a long, loosing one of the main goals of using MVP, which is, to decouple the view to test the main app code which is supposed to be in Presenters and classes which can be run in the JVM.
How can I detect if a new listener has been registered for any widget in my android app? Is there a place where I can intercept the listener when it's being registered?
I may be misunderstanding but you could do something like:
public interface ListenerChangeListener { // Feel free to remove the redundancy :P
public void listenerAdded(ListenerChangeEvent e);
public void listenerRemoved(ListenerChangeEvent e);
}
And
public class ListenerChangeEvent extends AWTEvent // or other class {
// Implementation
}
Finally, subclass your own custom widgets and modify the addXListener() and removeXListener() methods to fire your custom events if any have been added to the component. Then you just create your "Listener" class as per normal and implement your new Listener interface and so on.
It's a bit long and drawn out, again, I may have misunderstood exactly what you were after.
You can get a list of listeners on an object through a getter method (e.g. getActionListeners () on AbstractButton), and check if the one you have added is in the list.
I am thinking about implementing a user interface according to the MVP pattern using GWT, but have doubts about how to proceed.
These are (some of) my goals:
the presenter knows nothing about the UI technology (i.e. uses nothing from com.google.*)
the view knows nothing about the presenter (not sure yet if I'd like it to be model-agnostic, yet)
the model knows nothing of the view or the presenter (...obviously)
I would place an interface between the view and the presenter and use the Observer pattern to decouple the two: the view generates events and the presenter gets notified.
What confuses me is that java.util.Observer and java.util.Observable are not supported in GWT. This suggests that what I'm doing is not the recommended way to do it, as far as GWT is concerned, which leads me to my questions: what is the recommended way to implement MVP using GWT, specifically with the above goals in mind? How would you do it?
Program Structure
This is how I did it. The Eventbus lets presenters (extending the abstract class Subscriber) subscribe to events belonging to different modules in my app. Each module corresponds to a component in my system, and each module has an event type, a presenter, a handler, a view and a model.
A presenter subscribing to all the events of type CONSOLE will receive all the events triggered from that module. For a more fine-grained approach you can always let presenters subscribe to specific events, such as NewLineAddedEvent or something like that, but for me I found that dealing with it on a module level was good enough.
If you want you could make the call to the presenter's rescue methods asynchronous, but so far I've found little need to do so myself. I suppose it depends on what your exact needs are. This is my EventBus:
public class EventBus implements EventHandler
{
private final static EventBus INSTANCE = new EventBus();
private HashMap<Module, ArrayList<Subscriber>> subscribers;
private EventBus()
{
subscribers = new HashMap<Module, ArrayList<Subscriber>>();
}
public static EventBus get() { return INSTANCE; }
public void fire(ScEvent event)
{
if (subscribers.containsKey(event.getKey()))
for (Subscriber s : subscribers.get(event.getKey()))
s.rescue(event);
}
public void subscribe(Subscriber subscriber, Module[] keys)
{
for (Module m : keys)
subscribe(subscriber, m);
}
public void subscribe(Subscriber subscriber, Module key)
{
if (subscribers.containsKey(key))
subscribers.get(key).add(subscriber);
else
{
ArrayList<Subscriber> subs = new ArrayList<Subscriber>();
subs.add(subscriber);
subscribers.put(key, subs);
}
}
public void unsubscribe(Subscriber subscriber, Module key)
{
if (subscribers.containsKey(key))
subscribers.get(key).remove(subscriber);
}
}
Handlers are attached to components, and are responsible for transforming native GWT events into events specialised for my system. The handler below deals with ClickEvents simply by wrapping them in a customised event and firing them on the EventBus for the subscribers to deal with. In some cases it makes sense for the handlers to perform extra checks before firing the event, or sometimes even before deciding weather or not to send the event. The action in the handler is given when the handler is added to the graphical component.
public class AppHandler extends ScHandler
{
public AppHandler(Action action) { super(action); }
#Override
public void onClick(ClickEvent event)
{
EventBus.get().fire(new AppEvent(action));
}
Action is an enumeration expressing possible ways of data manipulation in my system. Each event is initialised with an Action. The action is used by presenters to determine how to update their view. An event with the action ADD might make a presenter add a new button to a menu, or a new row to a grid.
public enum Action
{
ADD,
REMOVE,
OPEN,
CLOSE,
SAVE,
DISPLAY,
UPDATE
}
The event that's get fired by the handler looks a bit like this. Notice how the event defines an interface for it's consumers, which will assure that you don't forget to implement the correct rescue methods.
public class AppEvent extends ScEvent {
public interface AppEventConsumer
{
void rescue(AppEvent e);
}
private static final Module KEY = Module.APP;
private Action action;
public AppEvent(Action action) { this.action = action; }
The presenter subscribes to events belonging to diffrent modules, and then rescues them when they're fired. I also let each presenter define an interface for it's view, which means that the presenter won't ever have to know anything about the actual graphcal components.
public class AppPresenter extends Subscriber implements AppEventConsumer,
ConsoleEventConsumer
{
public interface Display
{
public void openDrawer(String text);
public void closeDrawer();
}
private Display display;
public AppPresenter(Display display)
{
this.display = display;
EventBus.get().subscribe(this, new Module[]{Module.APP, Module.CONSOLE});
}
#Override
public void rescue(ScEvent e)
{
if (e instanceof AppEvent)
rescue((AppEvent) e);
else if (e instanceof ConsoleEvent)
rescue((ConsoleEvent) e);
}
}
Each view is given an instance of a HandlerFactory that is responsible for creating the correct type of handler for each view. Each factory is instantiated with a Module, that it uses to create handlers of the correct type.
public ScHandler create(Action action)
{
switch (module)
{
case CONSOLE :
return new ConsoleHandler(action);
The view is now free to add handlers of different kind to it's components without having to know about the exact implementation details. In this example, all the view needs to know is that the addButton button should be linked to some behaviour corresponding to the action ADD. What this behaviour is will be decided by the presenters that catch the event.
public class AppView implements Display
public AppView(HandlerFactory factory)
{
ToolStripButton addButton = new ToolStripButton();
addButton.addClickHandler(factory.create(Action.ADD));
/* More interfacy stuff */
}
public void openDrawer(String text) { /*Some implementation*/ }
public void closeDrawer() { /*Some implementation*/ }
Example
Consider a simplified Eclipse where you have a class hierarchy to the left, a text area for code on the right, and a menu bar on top. These three would be three different views with three different presenters and therefore they'd make up three different modules. Now, it's entirely possible that the text area will need to change in accordance to changes in the class hierarchy, and therefore it makes sense for the text area presenter to subscribe not only to events being fired from within the text area, but also to events being fired from the class hierarchy. I can imagine something like this (for each module there will be a set of classes - one handler, one event type, one presenter, one model and one view):
public enum Module
{
MENU,
TEXT_AREA,
CLASS_HIERARCHY
}
Now consider we want our views to update properly upon deletion of a class file from the hierarchy view. This should result in the following changes to the gui:
The class file should be removed from the class hierarchy
If the class file is opened, and therefore visible in the text area, it should be closed.
Two presenters, the one controlling the tree view and the one controlling the text view, would both subscribe to events fired from the CLASS_HIERARCHY module. If the action of the event is REMOVE, both preseneters could take the appropriate action, as described above. The presenter controlling the hierarchy would presumably also send a message to the server, making sure that the deleted file was actually deleted. This set-up allows modules to react to events in other modules simply by listening to events fired from the event bus. There is very little coupling going on, and swapping out views, presenters or handlers is completely painless.
I achieved something on these lines for our project. I wanted a event-driven mechanism (think of PropertyChangeSupport and PropertyChangeListener of standard jdk lib) which were missing. I believe there is an extension module and decided to go ahead with my own. You can google it for propertychangesupport gwt and use it or go with my approach.
My approach involved logic centred around MessageHandler and GWTEvent. These serve the same purpose as that of PropertyChangeListener and PropertyChangeEvent respectively. I had to customize them for reasons explained later. My design involved a MessageExchange, MessageSender and MessageListener. The exchange acts as a broadcast service dispatching all events to all listeners. Each sender fires events that are listened by the Exchange and the exchange the fires the events again. Each listener listens to the exchange and can decide for themselves (to process or not to process) based on the event.
Unfortunately MessageHandlers in GWT suffer from a problem: "While a event is being consumed, no new handlers can be hooked". Reason given in the GWT form: The backing iterator holding the handlers cannot be concurrently modified by another thread. I had to rewrite custom implementation of the GWT classes. That is the basic idea.
I would've posted the code, but I am on my way to airport right now, will try to post the code as soon as I can make time.
Edit1:
Not yet able to get the actual code, got hold of some power-point slides I was working on for design documentation and created a blog entry.
Posting a link to my blog article: GXT-GWT App
Edit2:
Finally some code soup.
Posting 1
Posting 2
Posting 3
have a look at: http://www.gwtproject.org/javadoc/latest/com/google/gwt/event/shared/EventBus.html
(which outdates http://www.gwtproject.org/javadoc/latest/com/google/web/bindery/event/shared/EventBus.html)
It should run fine with GWT as I'll try right now myself.