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

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.