How to implement Mediator Design Pattern with Fragments - java

I've been accustomed to making my views as dumb as possible and creating a ViewMediator wrapper class to handle all the "smarts" such as handle user interaction with the view and writing updates from the model to the view.
After reading up how fragments work, I am a bit of a loss as how will this workflow would continue to work. Orientation changes or garbage collections may cause the fragment to disappear and then reappear/restored to a completely new instance. So whatever reference that my ViewMediator referenced could be invalid. With activities, it wasn't so bad because I could always rely on the onCreate() method to re-instantiate all the artifacts.
My questions is how does one craft a fragment such that the behavior of it is separate from the fragment. Or should I be coupling the behavior into the fragment making it essential a Mediator as well. But that comes at the cost of attaching dependencies like the Model (where the Mediator reads & writes data) or the Controller (which needs it to fire off application wide behaviors).

Related

Best way to implement MVP [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
In the MVP pattern, there is no dependency between the view and the model. Everything is done by the presenter.
In our GWT-project, we implement all our MVP classes like shown on the GWT .page. To access the view, our presenter uses an interface like this:
public interface Display {
HasClickHandlers getAddButton();
HasClickHandlers getDeleteButton();
...
}
So, the presenter gets a button from the view, and applies its click handlers to it.
But this feels so wrong to me. This violates the single responsibility principle, as well as the information hiding principle. the presenter should not know anything of the internals of the view (even when we get an abstract HasClickHandlers).
In my opinion, we should better use this kind of pattern:
public interface Display {
void setPresenter(Presenter p);
}
public interface Presenter {
void onAdd();
void onDelete();
}
So, the view tells the presenter actively, that some interaction occured. But not on which view-element.
My team partners argue, that with the first solution, we avoid circular dependencies. That´s right. But anyway, I would prefer the second way because the modules are better separated and can be maintained independently.
What are the advantages / disadvantages?
Strongly agree - and the article you link describes both sides, if you continue to the second section.
I don't build my Views exposing widgets or their HasSomethingHandlers - I find it generally better to build the Presenter API to expose those possible interactions for several reasons:
Unit tests - It is simpler to make a mock view which invokes methods rather than firing events. This is not to say that it isn't possible (especially if your Presenter can run on the JVM and you can create a Proxy type for each one.
Cleaning up unused handlers - Presenters are generally cheap and get re-created each time, but sometimes Views are heavy and are saved, reused. Any time you reuse a view, you have to be sure that all of those externally added handlers were removed. This can be done correctly with some "lifecycle" methods like onStop() or something on the presenter, so that whatever code replaces presenters can shut it down, but would need to be factored in.
Multiple view implementations - like unit tests, different view implementations (mobile vs desktop, readonly vs readwrite, etc) might have different ways of causing the same change. Now, you could have multiple methods exposing HasClickHandlers onAddClicked() and HasTouchHandlers onAddTapped(), or, take the approach you describe. (You also can end up leaking some UX details into the presenter, like hitting the Enter key while in the last field, as opposed to clicking the button - that arguably belongs in the view, and not in the presenter).
One downside of this approach: the view needs more brains, and part of the goal of MVP is to keep the view as skinny as possible.
Finally, while this alternative approach isn't actually compared and contrasted on the page you linked, page two of the same article you linked does show your approach instead http://www.gwtproject.org/articles/mvp-architecture-2.html:
Now that we have the UI constructed, we need to hook up the associated UI events, namely Add/Delete button clicks, and interaction with the contact list FlexTable. This is where we’ll start to notice significant changes in the overall layout of our application design. Mainly due to the fact that we want to link methods within the view to UI interactions via the UiHandler annotation. The first major change is that we want our ContactsPresenter to implement a Presenter interface that allows our ContactsView to callback into the presenter when it receives a click, select or other event. The Presenter interface defines the following:
public interface Presenter<T> {
void onAddButtonClicked();
void onDeleteButtonClicked();
void onItemClicked(T clickedItem);
void onItemSelected(T selectedItem);
}
This is done in the context of describing the UiBinder way of building views, but it applies equally well without UiBinder.
So when discussing the article in relation to organizing how your team is building their application, be sure to consider the entire set of articles - those articles are both referenced from http://www.gwtproject.org/doc/latest/DevGuideMvpActivitiesAndPlaces.html, which also assumes this non-eventhandler approach. And in that article there are other "wrong" ways of doing things, like manual dependency injection, instead of an automated reliable tool like Gin or Dagger2.
The articles aren't meant to describe the One True Way, but to understand the ideas and patterns that can be used. Don't cargo cult this, applying patterns blindly, but make sure to understand the pros and cons - and work as a team, a pattern used inconsistently is arguably worse than no pattern at all!
EDIT: I realized I didn't mention the circular dependency issue!
This is as much or as little of an issue as you want it to be. If you create them at the same time, and pass references to the other in the constructors, obviously you have an issue - GWT can't proxy them (and arguably that's a bad idea anyway). But, down the road, you might get into a situation where views are expensive to build and could be pooled/cached and not re-created every time, in which case the view needs to be informed of the new presenter it now works with anyway.
That then requires that the View interface supports a void setPresenter(P) method anyway, so our circle is broken. Keep in mind also that this approach will require either the presenter being sure to clear out data in the view, or the view knowing when a new presenter is set to clear its own data.
My personal approach for this leads to the presenter owning a view field, injected (probably via constructor) when it is created, and have a start method in the presenter. When called, the presenter takes control of the view, and when ready, appends it where it belongs in the dom hierarchy.
Yes, this requires one extra method in the view, but if you have any base class for your views, this will be trivial, and if you end up doing any view reuse, you need that method anyway.

Clean Architecture: How to reflect the data layer's changes in the UI

I'm trying to make a design based on the Uncle Bob's Clean Architecture in Android.
The problem:
I'd like to solve is how to make the changes generated in one repository to be reflected in other parts of the app, like other repositories or Views.
The example
I've designed a VERY simplified example for this example. Please notice that boundary interfaces has been removed to keep the diagrams small.
Imagine an app that shows a list of videos (with title, thumnail and like count), clicking a video you can see the detail (there you can like/dislike the video).
Additionally the app has an statistics system that counts the number of videos the user liked or disliked.
The main classes for this app could be:
For the Videos part/module:
For the Stats part/module:
The target
Now imagine you check your stats, then navigate the list of videos, open the detail of one, and click the like button.
After the like is sent to the server, there are several elements of the apps that should be aware of the change:
Of course the detail view, should be updated with the changes (this can be made through callbacks so no problem)
The list of videos should update the "likes" count for the given video
The StatsRepository may want to update/invalidate the caches after voting a new video
If the list of stats is visible (imagine a split screen) it should also show the updated stats (or at least receive the event for re-query the data)
The Question
What are the common patterns to solve this kind of communication?
Please make your answer as complete as you can, specifying where the events are generated, how they get propagated though the app, etc.
Note: Bounties will be given to complete answers
Publish / Subscribe
Typically, for n:m communication (n senders may send a message to m receivers, while all senders and receivers do not know each other) you'll use a publish/subscribe pattern.
There are lots of libraries implementing such a communication style, for Java there is for example an EventBus implementation in the Guava library.
For in-app communication these libraries are typically called EventBus or EventManager and send/receive events.
Domain Events
Suppose you now created an event VideoRatedEvent, which signals that a user has either liked or disliked a video.
These type of events are referred to as Domain Events. The event class is a simple POJO and might look like this:
class VideoRatedEvent {
/** The video that was rated */
public Video video;
/** The user that triggered this event */
public User user;
/** True if the user liked the video, false if the user disliked the video */
public boolean liked;
}
Dispatch events
Now each time your users like or dislike a video, you'll need to dispatch a VideoRatedEvent.
With Guava, you'll simply pass an instantiated event object to object to EventBus.post(myVideoRatedEvent).
Ideally the events are generated in your domain objects and are dispatched within the persisting transaction (see this blog post for details).
That means that as your domain model state is persisted, the events are dispatched.
Event Listeners
In your application, all components affected by an event can now listen to the domain events.
In your particular example, the VideoDetailView or StatsRepository might be event listeners for the VideoRatedEvent.
Of course, you will need to register those to the Guava EventBus with EventBus.register(Object).
This is my personal 5cents and maybe not closely enough related to your example of "The Clean Architecure".
I usually try to force a kind of MVC upon androids activities and fragments and use publish/subscribe for communication. As components I have model classes that handle business logic and the data state. They data changing methods are only to be called by the controller classes which usually is the activity class and also handles session state. I use fragments to manage different view parts of the application and views under those fragments (obviously). All fragments subscribe to one or more topics. I use my own simple DataDistributionService which handles different topics, takes messages from registered publishers and relays them to all subscribers. (partly influenced by the OMGs DDS but MUCH MUCH more primitive) A simple application would only have a single topic e.g. "Main".
Every part of view interaction (touches etc) is handled by its fragment first. The fragment can potentially change a few things without sending notifications. E.g. switching the subrange of rendered data elements if the rest of the app does not need to know/react. Otherwise the fragment publishes a ViewRequest(...) containing the necessary parameters to the DDS.
The DDS broadcasts that message and at some point reaches a controller. This can simply be the main activity or a specific controller instance. There should be only ONE controller so that the request is only handled once. The controller basically has a long list of request handling code. When a request arrives the controller calls to the business logic in the model. The controller also handles other view related things like arranging the view (tabs) or starting dialogs for user input (overwrite file?) and other things that the model is not supposed to know about but influences (Throw new NoOverWritePermissionException())
Once the model changes are done the controller decides if an update notification has to be send. (usually it does). That way the model classes do not need to listen or send messages and only take care of busines logic and consistent state. The update notification ist broadcasted and received by the fragments which then run "updateFromModel()".
Effects:
Commands are global. Any ViewRequest or other kind of request can be send from anywhere the DDS can be accessed. Fragments do not have to provide a listener class and no higher instance has to implement listeners for their instanced fragments. If a new fragment does not require new Requests it can be added without any change to controller classes.
Model classes do not need to know about the communication at all. It can be hard enough to keep consistent state and handle all the data management. No message handling or session state handling is necessary. However the model might not be proteced against malicous calls from the view. But that is a general problem and cannot really be prevented if the model has to give out references at some point. If your app is fine with a model that only passes copies/flat data its possible. But at some point the ArrayAdapter simply needs access to the bitmaps he is supposed to draw in the gridview. If you cannot afford copies, you always have the risk of "view makes a changing call to the model". Different battlefield...
Update calls might be too simple. If the update of a fragment is expensive (OpenGL fragment reloading textures...) you want to have more detailed update information. The controler COULD send a more detailed notification however it actually should not have to/be able to know what parts of the model exactly changed. Sending update notes from the model is ugly. Not only would the model have to implement messaging but it also gets very chaotic with mixed notifications. The controler can divide update notifications and others a bit by using topics. E.g. a specific topic for changes to your video resources. That way fragments can decide which topics they subscribe to. Other than that you want to have a model that can be queried for changed values. Timestamp etc. I have an app where the user draws shapes on canvas. They get rendered to bitmaps and are used as textures in an OpenGL view. I certainly don't want to reload textures everytime "updateFromModel()" is called in the GLViewFragment.
Dependency Rule:
Probably not respected all the time. If the controller handles a tab switch it can simply call "seletTab()" on a TabHost and therefore have a dependency to outer circles. You can turn it into a message but then it is still a logical dependency. If the controller part has to organize some elements of the view (show the image-editor-fragment-tab automatically after loading an image via the image-gallery-fragmen-tab) you cannot avoid dependencies completely. Maybe you can get it done by modelling viewstate and have your view parts organize themselves from viewstate.currentUseCase or smth like that. But if you need global control over the view of your app you will get problems with this dependency rule I'd say. What if you try to save some data and your model asks for overwrite permission? You need to create some kind of UI for that. Dependency again. You can send a message to the view and hope that a DialogFragment picks it up. If it exists in the extremely modular world described at your link.
Entities:
are the model classes in my approach. That is pretty close to the link you provided.
Use Cases:
I do not have those explicitly modelled for now. Atm I am working on editors for videogame assets. Drawing shapes in one fragment, applying shading values in another fragment, saving/loading in a galleryfragment, exporting to a texture atlas in another one ... stuff like that. I would add Use Cases as some kind of Request subset. Basically a Use Case as a set of rules which request in which order are allowed/required/expected/forbidden etc. I would build them like transactions so that a Use Case can keep progressing, can be finished, can be cancelled and maybe even rolled back. E.g. a Use Case would define the order of saving a fresh drawn image. Including posting a Dialog to ask for overwrite permission and roll back if permission is not give or time out is reached. But Use Cases are defined in many different ways. Some apps have a single Use Case for an hour of active user interaction, some apps have 50 Use Cases just to get money from an atm. ;)
Interface Adapters:
Here it gets a bit complicated. To me this seems to be extremely high level for android apps. It states "The Ring of Interface Adapters contains the whole MVC architecture of a GUI". I cannot really wrap my head around that. Maybe you are building far more complicated apps than I do.
Frameworks and Drivers:
Not sure what to think of this one. "The web is a detail, the database is a detail..." and the graphic contains "UI" in this Ring as well. Too much for my little head
Lets check the other "asserts"
Independent of Frameworks. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.
Hm yeah well, if you run your own architecture that is what you get.
Testable. The business rules can be tested without the UI, Database, Web Server, or any other external element.
As in my approach model classes neither know about controllers or views nor about the message passing. One can test state consistency with just those classes alone.
Independent of UI. The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.
Again a bit overkill for android is it not? Independence yes. In my approach you can add or remove fragments as long as they do not require explicit handling somewhere higher up. But replacing a Web UI with a console UI and have the system run like before is a wet dream of architecture freaks. Some UI elements are integral part of the provided service. Of course i can easily swap the canvas drawing fragment for a console drawing fragment, or the classic photo fragment for a 'take picture with console' fragment but that does not mean the application still works. Technically its fine in my approach. If you implement an ascii console video player you can render the videos there and no other part of the app will necessarily care. However it COULD be that the set of requests that the controller supports does not align well with the new console UI or that a Use Case is not designed for the order in which a video needs to be accessed via a console interface. The view is not always the unimportant presenting slave that many architecture gurus like to see it as.
Independent of Database. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.
Yeah, so? How is that directly related to your architecture? Use the right adapters and abstraction and you can have that in a hello world app.
Independent of any external agency. In fact your business rules simply don’t know anything at all about the outside world.
Same here. If you want modularized independent code then write it. Hard to say anything specific about that.

GWT - Separating role of presenter from activity

What advantages could be gained from divesting the role of presenter from an activity?
What are the roles/concerns that could be separated in order to dissect an activity from being a presenter?
Why would you want to separate them into two distinct concerns?
Under what circumstances would it make sense not to unify them?
Give examples, pros or cons.
I can see two main reasons to separate presenters from activities: reusability and testability.
Real use case for reusability: we have an illustration entity with properties like the photographer, copyright and date of shooting, which can be linked to documents. The legend of is on the relationship between the document and the illustration. You can edit both the illustration and the legend on their own screen, but we also wanted that the illustration could be edited from the legend screen. So we made a presenter for the illustration screen. The illustration activity is a really thin wrapper around that presenter, and the legend activity is a bit more complex, but reuses the presenter and view. The activities' responsibility is to provide the RequestContexts and do the fire() (the save/cancel buttons are on another activity, similar to the actions on Google Groups).
Hypothetical use cases for reusability:
for different form-factors, you want to aggregate things on the same screen or separate them on their own screen (e.g. master/detail), and when you aggregate them, having two activities might not be ideal. Using thin activities in the phone form-factor allows you to reuse the components (presenter/view) within a single activity in the tablet or desktop form factors.
reusing the same presenter on different platforms: you could possibly use the same presenter on an Android app and a web app (and even possibly an iOS app through java2objc), the view would be a native Android view or a GWT-based view, and the navigation would be handled by Android activities and/or fragments vs. GWT activities and places.
About testability (this is theoretical), you could then test your presenter without the hassle of the activity lifecycle (mocking the view), and then separately test the lifecycle (whether it correctly initializes and cleans up the presenter, fetches/caches the data, etc. mocking the presenter).
See also the commit message of https://code.google.com/p/google-web-toolkit/source/detail?r=10185
Ray's idea was to make MVP an implementation detail of widgets, just like cell widgets use internal presenters today. From the outside they're just widgets that you can compose tha way you want; on the inside they use MVP so you can test them without the need for a GWTTestCase.
First of all two Thanks for question which pushes me in to the longest research ever . :)
According to Thomos Broyer here.
Activity cannot talk with widgets,which presenter can do.
Two main areas of concern:
1- getting the data into the widgets:
how can this design be improved ?
Server (RequestFactory) ---> Activity ---> WidgetPresenter ---> Widget
here, RequestFactory hands in data to Activity, which then gives it to
the Presenter
which subsequently hands it to the widget.
2- getting the data from the widgets to the server
widget ---> WidgetPresenter ---> Activity ---> Server(RequestFactory)

Keeping things decentralized Android

This might not make much sense in terms of Android SDK, but, in C++ I am used to keeping my main.cpp (and specifically main() function) as a place where I declare and initialize other classes/objects, and afterwards all the things that my application does take place in those classes. I never come back and check for anything in main.cpp afterwards.
But in Java, Android SDK, you have to override dozens of methods in main activity and all of that takes place in one single file. Example:
I have a MainActivity.java and SomeTest.java files in my project, where first is default MainActivity class which extends Activity, and SomeTest.java contains class that declares and runs new Thread. I initialize SomeTest class from MainActivity.java and pass a handle of the activity to it as a parameter:
SomeTest test = new SomeTest(MainActivity.this);
And having the handle to MainActivity, I proceed doing everything from this newly created thread. When I need to update the UI I use runOnUiThread() to create and show a new ListView (for example) on my main layout. I want to get the width and height of the newly created Listview, for what I have to override onWindowFocusChanged() in my MainActivity.java and notify the thread from there, as getWidth() and getHeight() will only have values when ListView is actually displayed on the screen. For me it's not a good practice to make such connections ('callbacks', if you will) from MainActivity to that thread.
Is there a way I can keep methods like onWindowFocusChanged() within the thread and don't touch the MainActivity.java at all?
As I said, might not make much sense.
Is there a way I can keep methods like onWindowFocusChanged() within the thread and don't touch the MainActivity.java at all?
onWindowFocusChanged() is a callback method. It is called on the activity. You cannot change this.
And having the handle to MainActivity, I proceed doing everything from this newly created thread.
That's generally not a good idea. Using a background thread to, say, load some data from a file or database is perfectly reasonable (though using Loader or AsyncTask may be better). However, usually, the background thread should neither know nor care about things like "the width and height of the newly created ListView".
You are certainly welcome to migrate some logic out of the activity and into other classes. You might use particular frameworks for that, such as fragments or custom views. However, the class structure should not be driven by your threading model. For example, let's go back to your opening statement:
in C++ I am used to keeping my main.cpp (and specifically main() function) as a place where I declare and initialize other classes/objects, and afterwards all the things that my application does take place in those classes
However, in C++, you would not say that you are locked into only ever having two classes, one of which is operating on some background thread. While you may have a class or classes that happen to use a background thread (or threads), the driving force behind the class structure isn't "I have a background thread" but "I want to reuse XYZ logic" or "I wish to use a class hierarchy in support of the strategy pattern" or some such.
Personally speaking Context idea taken from Android SDK seems to be messy. What you are describing comes from too much responsibility intended for Activity. That's why you need to track a LOT of things inside single file (Activity's life cycle, getting Context instance in order to show Dialog etc.). I don't think there's perfect solution but I would recommend using:
Fragment subclasses which are helping to divide your screen (and so on logic) into seperate parts
3rd party frameworks/libraries like AndroidAnnotations, RoboGuice, Otto which are perfect tools to avoid spaghetti code
if you would like to perform some UI updates from another class, consider using an AsyncTask passing it the Views you need to update. Let me know if you need an example
I read everything and understand your statements, I can see you've been doing programming for sometime but apparently is just starting with Android, I've done a lot of embed systems before so I totally get the concept of having a software that looks like:
void run(){
object.setup();
while(true){
otherObject.run();
}
}
But there's one fundamental flaw on the you logic of your question:
Android programming is a different programming paradigm from C++ and from computer programming and you should understand its specific paradigm instead of assume what is good practice from other paradigms.
Quote from you: create and show a new ListView (for example) on my main layout. I want to get the width and height of the newly created Listview, for what I have to override onWindowFocusChanged().
From that I can see that you've really trying to do Android stuff on a way that is not recommended on an Android context. A ListView you can easily implement from the XML layout setContentView(int) and use the Activity onCreate to instantiate any threading (AsyncTaskLoader) framework to load the data in background and deliver it back to the UI.
That doesn't mean that all your code will be dumped in one file making it a mess. This little example I put you can do with Activity that implements the loader callbacks, a separate class with the loader, a separate class with the data loading work, a separate class with the data adapter, the activity is just a central piece that organise and manage those classes on the correct moment of its life-cycle and at no point you need to call onWindowFocusChanged() and still have a nicely organised code.
Apart from that please refer to CommonsWare answer as it's usually cleverly written and correct.

Android: Using observer pattern with Views (possibly MVC, MVVM related)

I've spent some hours reading various questions and answers regarding implementing the various MVC-type patterns in Android. I've seen a few code examples posted in various blogs. I would, however, still appreciate some ideas and opinions on what I am trying to achieve. Specifically, I'd like to work out the best code mechanism to inform a single View, or a group of Views, that a particular item of data has been changed.
My application is quite simply one which obtains measurement data from a hardware device via Bluetooth, and displays and logs that data. At present, I have a Service which takes care of Bluetooth communications and background logging. I have a 'global' data store class that is an extension of Application.
As measurement data is polled from the external device, the measurement data (which is in reality about thirty bytes of data) is updated in the data store object (which, in MVC terms, I'm guessing is the 'model').
At any time, only a small subset of that data will be displayed by UI Views. Typically, a given View will only be interested in representing one particular byte of measurement data. As the user moves to different Activity classes, other Views will be displayed which would display a different subset of that data.
So to get to the point, I'm trying to choose the best way to cause invalidate() to be invoked on interested Views when a given data item is changed.
The options seem to be:
Make use of the existing Observer class, and related classes.
Kind of 'roll my own' observer pattern, by creating my own register() and unregister() functions in the data model. Observer Views would be held in an ArrayList (or perhaps a more complex arrangement of one observer List per data item). I'd loop through this ArrayList each time data are updated and call invalidate() (or postInvalidate() of course, depending on my threading arrangement).
Are there any reasons why I should use one of the above over the other? And is there any other 'observer' mechanism I should consider?
Many views in Android are backed by some subclass of BaseAdapter which has a method notifyDataSetChanged() which instructs the view to refresh itself. If you are using a view (such as ListView or GridView or any descendent of AdapterView) then it is backed by a BaseAdapter and you can simply update that Adapter and the view will refresh itself.
I guess this means, I vote that you use the built-in observer pattern. If you are using a custom view then obviously this won't work and you would have to use a custom method of refreshing anyway.
Another Option would be to use the Android Intent framework. When new data is received in the service set the data to the universal model and broadcast an intent that the data has been updated using the Context.broadcastIntent(Intent) method. Any view that is interested in that data would register and unregister receivers using the Context.RegisterReceiver(Receiver) and Context.unregisterReceiver(Receiver) methods. From there the view would retrieve the data from the universal model and update the view accordingly.
I think this might be what the observer pattern in Android.Lifecycle.Observer package is doing behind the scenes.

Categories

Resources