I have an architectural question. Currently my app is so simple that user logs in and gets a list of restaurants and he can logout. I use kotlin coroutines for async part, mvvm live data and koin DI.
Here is my login flow when user clicks on login. The regex validation is done in LoginViewModel -
LoginFragment -> LoginViewModel -> AccountUseCase -> AccountRepoImpl -> AccountLocalDataSource or AccountRemoteDataSource
And the response is given all the way back from DataSource to LoginFragment.
I consider the AccountUseCase and AccountRepoInterface as a part of the domain folder along with the AccountModel. The AccountRepoImpl is in repo folder and AccountLocalDataSource and AccountRemoteDataSource is in datasource folder.
My question is ideally the domain should not have any 3rd party dependencies. But my AccountUseCase emits livedata to the viewmodel class and as a result my domain is using android livedata dependency and also it is not doing much but just calling the repo for loginuser. Does it make sense then to have this usecase?
In terms of the LiveData dependency, I would suggest you to ignore it in this case. If you want to make it reactive, either you use library like LiveData or RxJava or have your own implementation. There's no much difference. Just that LiveData happen to be provided by a package that has the word android inside.
Regarding the use case, as you said your app is currently simple. The use case seems redundant for now as the logic is simple in this case but it will be helpful once the app gets more complex.
Some scenarios that I can think of:
when the login logic changes, you only have to update the AccountUseCase which follows the Single Responsibility Pattern (SRP).
when you want to use the AccountUseCase in other ViewModel instead of reusing the whole LoginViewModel.
this makes your code base more consistent, if all the logic are inside the domain layer. Instead of "hiding" some simple logic inside your ViewModel.
Related
I'm a beginner studying MVVM design patterns.
Looking at the code of Google CodeLab and other sample codes, a question arose.
As the title suggests, does LiveData necessarily exist in the Repository?
I've been using and observing LiveData in a ViewModel so far.
(There's no special reason, I just used it because I didn't know anything)
By the way, I looked at the code of Google CodeLab to study Room, and I saw that it uses LiveData (or Flow) in the Repository and reference this in LiveData of the ViewModel.
Sample code from other web sites was similar.
But I don't know why LiveData is in the Repository and uses the way it's referenced.
Since LiveData is used in the Repository in the code of official docs such as CodeLab, I am using it accordingly, but I do not know why.
In the MVVM pattern, does LiveData necessarily exist in the Repository? I'd appreciate it if you could explain why.
LiveData is simply an observable data holder. It is lifecycle aware so it is a good practice to use it for providing data to View from ViewModel. LiveData can now be replaced with Flow which have few benefits over LiveData.
From Repository to ViewModel, it is completely up to you whether you want a LiveData/Flow returned or simply return the model that you expect from DAO but still you will require a LiveData/Flow if you want to provide that model to View after receiving that model from Repository to ViewModel.
The MVVM pattern is more about designing software, and organising the architecture into separate layers. The View is the user-facing frontend, the Model is the backend where the data is handled.
The View Model sits between them, converting data from the Model into some form of UI state the View can display, and turning UI events like button presses into calls to the app's backend functions, in the Model.
LiveData and Flow (which are similar - one is Android and one is Kotlin) are ways of exposing data, which is ultimately what the Model does - producing data. Instead of just providing a single value on request, they're able to provide a stream of data.
And the View Model (which is the intermediary between the Model and View - they don't talk to each other) can take that LiveData or Flow, and either expose it directly to the View, or do some processing on it to produce data suitable for the View to display. That way you have a pipeline from the data producer (the Model) to the UI (the View). That's basically how MVVM works in general, this is just using the streaming/producer/reactive model to wire things up and make things like async operations simpler
This is worth a read, it explicitly mentions repositories as the data producer in this model:
https://developer.android.com/kotlin/flow
I don't understand few things about repository in mvvm, also have seen multiple blogs and code templates. Every one of them doesn't match with other. So
Why there is needs to have multiple Repositories classes? Why single repository shouldn't handle all the data IN OUT for the app?
Why Repository shouldn't be a SINGLETON class in project?
What a repository('s method) should provide to viewmodel Result(Sealed class) or actual response from a api like list(or error)?
SharedPrefrences should be handled by Repository as well or not? if no why
I believe Repository should be that part of your code which should process all the data from multiple source whether be database or network or sharedprefs. So what do you think?
Purpose of repository is not only to manage requests/response but also provide a layer to keep responsibilities separated. If you have 2 modules (let's say Login and Registration), it is much better to keep repositories separated to keep things clean and simple rather than having a single repo with spaghetti code.
This point is opinionated. IMO you can have singleton repositories because they are stateless i.e they do not hold any kind of data which may cause conflict between multiple ViewModels/Modules.
Depends on you but it is much better to return Result. With Result you can handle Success Failure and Error Messages easily and return different Error Messages directly from repository rather than deciding in ViewModel what message to show. Messages can be either from server or internal exception messages.
SharedPreferences is a datasource. Yes you can manage preferences using repository pattern.
I couldn't find any source that answers this question directly:
Are Android Architecture Components made to follow an MVVM architecture (if implemented properly)? And if yes, which part of the app (Activity/Fragment, ViewModel, repository, database, web service) relates to "Model" "View" and "ViewModel"?
The ViewModel class obviously belongs to the ViewModel layer, but what about the rest?
Your Activity or Fragment is your VIEW,particular activity/fragment viewmodel represents VIEWMODEL which contains all the business logic of your UI and Model/Repository represents MODEL which contains all the data related logics. You can manipulate data in model and can use Database,web services and Shared Preferences in the Model.
I've seen good examples of MVP architecture (here and here). Both present only simple interactors, but I wonder how to deal with more complex use case, consisting of steps, which are repeated in other use cases.
For example, my API requires token to authenticate any call. I've created an interactor to get that token (GetToken). I want to get user's last login date (GetLastLoginDate) and then fetch a list of changes that occured between that date and now (GetVersionChanges).
Where those interactor should be chained? I want to keep them separate, because some of them are reused in other parts of the code. I've came up with two solutions.
Presenter should chain all interactors. This solution works as long the use case is not complex and doesn't have many preconditions. It seems to me it's not the right place, because it burdens presenter with another responsibility.
Interactor can use many repositories (no clean architecture rules are broken then). Why not use TokenRepository in other interactors? Because getting token is much more complex than just reaching to repository. Repeating the steps in other interactor does not reuse already existing code.
Both solutions have their flaws and are against basic principles (DRY, single responsibility principle).
If I were you I would just put the logic of getting a token in a separate interactor (maybe named getTokenInteractor) and call that interactor from your others interactor who may need it.
That way, it would be in an interactor that you chose either to use a token (and call or not your getTokenInteractor) and also in an interactor that you retrieve it and deal with errors.
I would do the same for your "getVersionChanges" use case and let an interactor chain the calls.
Let's imagine you have a presenter who needs to display the version changes. He will call a first interactor (GetVersionChangesInteractor) who will first check if he has a token (by calling getTokenInteractor), then call GetLastLoginDateRepository for retrieving the date, and call GetVersionChangesRepository with that date and finally give the result to your presenter.
That way, your business logic can stay 100% in your interactor and your presenter can focus on how he will display that on screen.
By the way, if your API needs a token for every call you should move it in an Interceptor so you do not have to deal with it at every call.
It's possible that the MVPC pattern is what you're after. This is something I wrote ages ago on it (though the code example is pretty poor so please excuse that!)
Recently I started reading a lot about MVP and I want to get into practicing my projects with it.
However I am not able to correctly understand where should Rx + Retrofit code go? I think it should be in Model Layer via Interactors but still can someone share some light on this?
Also what happens with the RX callback? the onNext(), onCompleted() and onFailure() passes data back to Presenter or do we implement listeners and then pass it on to Presenter?
I also want to persist data (Realm/StorIO) when I get it in onNext(), So again pass it to another DataLayer or where should it Go?
Also should we decouple Rx callbacks further?
I am following this post
https://davidguerrerodiaz.wordpress.com/2015/10/13/a-brief-introduction-to-a-cleaner-android-architecture-the-mvp-pattern/
and this seperate github repo from antonioleiva.com
https://github.com/antoniolg/androidmvp
As you pointed the RxJava functionality defines a use case of your model layer so it would be placed in an interactor of this layer. You can create a different interactor for each use case. Let's say you are pulling a list of users from your server, this would be a use case and an interactor that will have the RxJava/Retrofit Observable.
Then you will have a Presenter with an Observer in it which is interested in this users list, so it will be subscribed to that Observable.
And finally when this Observer in has all the data from the Observable (onCompleted), it will transform this data (if needed it) and pass to the View which will be just in charge of display it.
There is awesome post explaining mvp.
Rx is just additional tool for it.
http://hannesdorfmann.com/android/mosby-playbook/
there is deep explanation and source code with example.