Clean architecture. What are the jobs of presenter? - android

I have been reading some articles about the clean architecture, and how it can be implemented in android. I saw the sample app which shows its Android Implementation. Also, I went through a nice talk on Clean architecture on Android
So, I kind of understand most of the concepts, but there is some clarity that I would like to get on certain things.
As per my Understanding,
The View layer is the outer layer which deals with the UI, and
framework related stuff
The presenter is the direct communicator for the view, which accepts user inputs, and executes certain use cases based on this by passing it to the use case layer or the interactor layer.
Interactor executes the use-case, give it back to the callback sent by presenter,
Presenter again converts this result into a view understandable data structure (a ViewModel) and just pass it back to the view.
I am not listing more details about the inner layers like repository since my question is related to the above-mentioned steps
Here, does the presenter have the only job of acting as a mediator between UseCases and UI, as a data dispatcher?
Does it only do the view model to use case model conversion and vice-versa?
The input validation logics rely on which layer? Can it be inside the presenter? For example, if we take a small use case of a sign-up process,
Once the user entered the details and clicked sign-up button, and data sent to the presenter, is it like
Presenter validates the input values if any error is there notify
the view
If values are proper, convert it to a use case model, and execute
certain use case, and once the result is given by the interactor,
again convert to view model, send it to view.
And the second question is, who controls the navigation? The View or the Presenter or the UseCase?
who decides where to go next?
For example - Consider a use case of a login process, Where user will enter the credentials and click OK.
On successful login,
If users e-mail is not verified, go to email verify screen
If users profile is not completed, set-up the profile then only go to home screen
If user is new, show new offers screen, else directly go to home screen
So, who is responsible for making these decisions on which screen to go next? Is it the presenter, which decides and navigate the view accordingly? Or is it the use case handlers responsibility to inform the presenter what is the next State?
Sorry for making the question too long, but I just wanted to elaborate my current understandings. Thanks in advance

Here, does the presenter have the only job of acting as a mediator
between UseCases and UI, as a data dispatcher?
Yes
The input validation logics rely on which layer? Can it be inside the
presenter?
validation should rely on business layer not the presentation, can it be inside the presenter? sure it could, but what if you have multiple screens that take similar inputs, do you have to repeat your validation logic inside each presenter! you can argue that you can make a base presenter, but it's not the perfect solution, because presenter should have one purpose.
And the second question is, who controls the navigation? The View or
the Presenter or the UseCase?
do you consider the navigation is part of the Domain or the presentation or the data layer, it's likely related to the presentation layer, but you could make a small component inside the presentation layer which is control the whole navigation generically, So you can use this component the moment you decide that you do need other platform and throw your activities away. you can find this approach in the sample you've mentioned.
EDIT:0
How you pass data between modules where they have different models?
you simply use mappers, and the reason is to make each module has its own models or entities, so it would be easy to test each module separately.
About presenter and view, let's say you want show error message, presenter decides why it would be shown, view decides how it would be shown.
I think the problem in understanding the clean code presentation layer with Android, that Activities and fragments aren't only view, they're also The process and the lifecycle which your code would be live in, clean code came along to separate spaghetti code on those Activities and fragments.
EDIT:1
adding to the last point, it's clear now that Google and the support team there made a great effort to make Activities and Fragments dummy views as possible via introducing the great set of libraries "Architecture components". I encourage anyone to check them out, even if you're using MVP, you'll find a great benefits.

Related

Discuss using Kotlin Coroutines with MVVM?

I am using Kotlin Corountines with MVVM pattern and faced a problem: The data processing part is being done inside the ViewModel. While the repository seems not really necessary. When the application needs to call many APIs, the ViewModel will swell. What is everyone's solution to this problem? Thank you
The repository is needed, because in the case when you have a large app and gave too much responsibility to the ViewModel it's broke the separation of concerns principle.
Basically in the Andorids Guide to app architecture :
A first idea for implementing the ViewModel might involve directly
calling the Webservice to fetch the data and assign this data to our
LiveData object. This design works, but by using it, our app becomes
more and more difficult to maintain as it grows. It gives too much
responsibility to the UserProfileViewModel class, which violates the
separation of concerns principle. Additionally, the scope of a
ViewModel is tied to an Activity or Fragment lifecycle, which means
that the data from the Webservice is lost when the associated UI
object's lifecycle ends. This behavior creates an undesirable user
experience.
Instead, our ViewModel delegates the data-fetching process to a new
module, a repository.
And direct answer for your question:
Even though the repository module looks unnecessary, it serves an
important purpose: it abstracts the data sources from the rest of the
app. Now, our UserProfileViewModel doesn't know how the data is
fetched, so we can provide the view model with data obtained from
several different data-fetching implementations.
Basically, you can give all work to your ViewModel, but it's not recommended.
If you work/planning to work as a dev, maintaining your code, make it flexible to change and understandable for others is also important and usually, everyone appreciates this

In MVVM, is the ViewModel always necessary?

I'm new to making android apps, Kotlin, and just trying to get my head around the MVVM design pattern.
I'm attempting to make a login screen while also integrating well with my team's existing code. Making the login screen work went well until I noticed that I was running into life-cycle issues with uninitialized lateinit vars (even though the code definitely ran the initialization statements) like SharedPreferences or the username and password fields etc.
After reading up more on MVVM, I believe that the existing code which I was learning from (which contains lateinit vars for Context, the Fragment, and View within the ViewModel etc) is fundamentally flawed and fails to decouple the ViewModel from the View life-cycle.
However this has me confused. To my understanding, the ViewModel is supposed to contain the business logic and any data which we want to survive configuration changes. On the other hand, the LoginFragment should only contain UI and OS interactions such as displaying the View or capturing input.
The LoginViewModel only contains code interfacing between the elements of fragment_login.xml and SharedPreferences, or logging errors:
resetFields(): empties the fields to blank
onLoginButtonClicked(): just calls the Retrofit function to POST the username/password a server for authentication
onLoginSuccessful(): saves the data to SharedPreferences
onLoginUnsuccessful(): changes the field's error message and logs the error
Because I used DataBinding on the xml elements, nothing (as far as I can tell) needs to be independent of the life-cycle (or rather, several things require access to the context or fragment!).
What is the proper way to go about this? Currently I am thinking that the ViewModel simply shouldn't exist and that all functionality (of which there is very little) should actually just be within LoginFragment). I was considering learning about and using LiveData next, but I just can't see how LiveData or ViewModel are necessary in this situation.
The main goal of any architectural pattern is to achieve Decoupling, Single responsibility and restricting Anti Patterns, to be precise code should be more readable, scalable and easily testable.
I know in some instances using this patterns might seem redundant for your use case, but always keep scaling in mind when ever developing even a simple feature. This will pay off in long term and help peers understand and isolate code better.
In Android, always remember view or UI(Activity/Fragment) should be as dumb as possible, only responsibility of them should be to listen to user touches and display data, by doing so you can test all your logic in isolation without relying on Android Framework.
MVVM is once such pattern designed keeping pain points of Android in mind, it does not cause any harm using it when needed to delegate even simple tasks like storing data to preferences, minor transformations to data before displaying. Let's say you have a static page which just displays static data using String and nothing else then you can avoid ViewModels.
MVVM pattern does not enforce you to use ViewModel for every Fragment/Activity, it recommends using it when needed as a best practice, ViewModel is just a data holder which persists configuration changes.

Android MVVM design - should i split my viewmodel class in two?

I have an app with 2 distinctly seperate modes, (setup and run timers).
The app allows multi factor inputs from a user on one fragment and once the user wants the timer started, the app switches to a running fragment to show information about their running timer and it's setup.
I've designed an MVVM architecture for this, with my own class that extends ViewModel, my shared viewmodel has two distinctly different types of logic, setup logic (to check, parse and revise inappropriate user inputs), and running timer logic (to manage all the logic, data and state for a running timer from a user's inputs).
My shared viewmodel class is not small as the process of checking all permutations of user input is complex.  I'm wondering is it a bad idea to put all this logic into one viewmodel class? The setup portion is designed to be simple and all setup state is saved (so 10-20 seconds for the user to setup a timer seems appropriate), whereas the timer is designed to be allowed to run for hours, largely with the screen off.
 
Should I split the viewmodel logic into two different viewmodel classes to make a running timer more memory efficient?
I see a clear seperation of concerns and once I have my Room database designed and programmed, only the running timer will save data to the database. I want to keep the fragment classes as lightweight as possible.  If this is a sensible design choice, ill need to be careful with memory leaks between the two states, otherwise im defeating the purpose.
Edited to differentiate between the ViewModel object and a Shared viewmodel idea
As a_local_nobody says, it's up to you to decide how to design your app and distribute the responsibilities.
In case you are looking for our opinion about your philosophical doubts, I have to say that although the concept of the Shared ViewModels is very widespread, I am not a big fan.
In my projects, the most common and logical thing is that each ViewModel manages the logic of a single view. I always treat Shared ViewModels as an exception to the rule, since abusing them usually leads to a very tightly coupled code, very difficult to test and with unexpected side effects.

Android MVP communications

I'm very new to MVP and can't seem to grasp this concept.
Basically I have an activity which has an onClick which displays a DialogFragment. The activity does what it needs to do with MVP. The DialogFragment does too. However they are fully independent with regards to linking to each other which is posing a problem for me. When the DialogFragment chain is finished doing what it needs to do, the presenter on this layer holds the data to update the view on the Activity layer. I want the presenter in the DialogFragment layer to give the data to the presenter in the Activity layer who can easily let their view know as it's already linked up nicely.
I've thought of interfaces, read about eventBus (I know nothing about this so be kind).
There must be a specific way of achieving this because it must be a common task, I know I'm going to be doing it a few times in this application.
Your model is the data source in MVP.
Don't know if I got your case properly or not but the model is responsible for providing data to the presenters.
So generally, your other presenter should be accessing the data it needs from the model. Your first presenter can ask the model to do insertions or updations etc required as per the business logic.
Once the alterations have been done by the model, your second presenter can access the data by asking for it from the model.
Hope, I made that out clearly.

Confusing term Interactors in Clean Architecture

As per clean architecture, design Interactor is part which contains all business logic. The term Interactor is quite confusing to me. Interactor seems to me like interacting between two different layers like data and presenter.
Is it the right term to use?
Can anyone please clear the purpose of Interactor? Which pattern does it follow?
If Interactor is not what it seems to me then what is the design pattern for
layer-layer interaction?
An Interactor is a design pattern that has nothing to do with "business logic" concept. Without going in deeper level of detail the Interactor pattern is an extension of the Command pattern; Each "business logic" object is treated as a "black box", a simple instruction to be executed for the client, decoupling the object that invokes the operation from the one that knows how to perform it. (refer to the bibliography for extended explanation).
In the android enviroment there is a simple 'rule' that demands to the programmer to do long time consuming task in a background thread, so the interactor patterns extends the "Command pattern" adding a layer of threading. All this complex stuff is implemented to create a "clean architecture" which entails a code that is scalable, maintainable and (arguably) understandable.
About the question .. ¿what is the design pattern for layer-layer interaction? It could have more than one rigth answer, depends of the situation. You could use a simple Interface as the entry point, so you could use the Adapter pattern, or maybe the Facade pattern, or if you want to do something more advanced you could implement an eventbus system.
Source:
Design patterns explained simply - auth Alexander Shvets. page 14 (Adapter), page 32 (Command), page 47 (Facade)
In the clean architecture approach, the Use Case Interactor is a layer that express the specific business rules. The Use Case Interactor interacts with the Entities (agnostic business rules) to achieve the Use Case intention. Entities can be used in another applications, once they are agnostics, on the other hand, the Use Case Interactors are specific application objects.
Can be found in the Clean Architecture book by Robert C. Martin at chapter 20
If you're familiar with domain driven design, then an Interactor can be compared to an Application Service. Also, it is incorrect to say "As per clean architecture, design Interactor is part which contains all business logic." On the contrary, Entities would contain the business (application-agnostic) logic; whereas Interactors would contain the application-specific logic. The Interactors would call the Entities to fulfill a use case, where a use case might be something like Create Purchase Order.
Going back to using Clean Architecture terms that Robert Martin (Uncle Bob) uses in his training video Architecture, Use Cases, and High Level Design, Uncle Bob says the following:
Interactors are application-specific. That means that any application specific business rule belongs inside an interactor. The interactors achieve their goals with application-specific logic that calls the application-agnostic logic within the entities. For example, the CreateOrderInteractor invokes both the constructor and the GetId method of the OrderEntity. Clearly, these two methods are application-agnostic. It's the interactor that knows how to call those two methods to achieve the goal of the use case.
For your observation that the Interactor seems like it is interacting between two different layers like data and presenter, that job actually belongs to the Boundary. The Boundary sits between the delivery mechanism and the Interactor, where the delivery mechanism might be a desktop application, MVC app, API, etc. This keeps the actual application and business code separate and transferable from one delivery mechanism to another.
He also has a nice diagram in the Extras section showing the interaction if you purchase the video. It looks something like the following:
Delivery Mechanism ==> Boundary ==> Interactor ==> Entity
P.S. The video referenced above is highly entertaining and informational.
From what I'm reading, it's the equivalent of the Presenter in the Model View Presenter (MVP) architecture.
It does business logic, not store or display data. It create a separate layer independent of how or where data is stored or displayed. It only cares about inputs and outputs in any format. It could be used in a combination of the Observer, Adapter, and Façade patterns to be an interface for callbacks, a generic extension point of the code, and a decoupled entry point for any non UI or data-storage usage, respectively.
I assume it is called an Interactor because the View interacts with it to calculate values and refresh any displayed UI elements and it interacts with the Model objects to extract data. It could also interact with a database for CRUD operations, but I think that's mostly addressed in the Repository Pattern as that isn't really business logic.
Interactors provides implementations for various use cases. Ideally, there should be one interactor per use case but it may differ according to the scale of your application.
Now, why it doesn't make sense for every application? Imagine you have two applications. In the first app, you just need to read a user. In the other application, you just update the very same user. You would have two different interactors like GetUserInteractor and UpdateUserInteractor. If you think about it, UpdateUserInteractor would make no sense for the first application (and vice versa), right? But your business/domain logic for both applications can still be the same where the implementations of both services (read and update) are included, for example, in the regarding business/domain object (or as separate use-case objects). These objects obviously encapsulate application agnostic business rules as they can be plugged under two or more different applications.
The communication takes place between the app and users is often application-specific. As others already mentioned, you can have your interactors execute commands on user actions. Or you can go for another similar way. But the command pattern is really convenient and arguably make the whole code more consistent, uniform, and easy to understand.
Last but not least, the other important aspect of interactors are 'boundary interfaces' which are the classes that polymorphically deployed for both input and output delivery.
(PS: For example, in Android, with the new architecture components, Fragment/Activity can be thought as an implementation of the input boundary as you deliver input events down to your business logic (or domain model) - it's the controller. LiveData is more like the output boundary implementation as it uses observer pattern under the hood and deliver the data back to the UI through the interactor. In this case, I think this makes the ViewModel a strong candidate for being the interactor since it receives the input events (and commands corresponding those events) and also contains the LiveData instance to be observed. Are all these decoupled nice, or, polymorphically deployed? Well, this is mostly related to your design. And with coroutines, now it seems like there's no need for callbacks/listeners - so another dimension into this picture.)
This is my take. I hope it's clear.
It's MVP pattern. Yes as you said it's mediator between presenter and data(as a form of rest call or shared preference or Sqlite).

Categories

Resources