I'm studying Android MVVM design pattern but I can't understand the right collocation of activity and fragment. It is correct to say that activity/fragment belong to the View layer?
MVVM is Model View ViewModel, an architecture and design method
when you talk about View layer for example in clean Architecture, you have this schema :
View Layer | domain Layer | data Layer
Activity/fragment | UseCase / Repository | Api/DAO/RespositoryImpl
viewModel | |
Related
When using Jetpack Compose navigation, would one use one ViewModel for all screens or one ViewModel for each screen? Is there any architecture guidance on this? And if one would use multiple ViewModels, where would one instantiate them?
I'm no professional when it comes to architectural design in software but I think that it all depends on your app's structure. Compose is basically a UI framework, and it's not a replacement for ViewModels. This means that you still have all the flexibility to go about it any way you see fit.
For example, if you have multiple different screens (i.e. Login, Home, Settings, etc.), you're probably better off using a separate ViewModel for each screen. If you have a very simple one-pager, you could get away with a single ViewModel.
The official docs have a pretty good description on how to go about structuring your app. You should obviously make any necessary adjustments in order to make the architecture fit your projects needs & goals.
As for the instantiation part, you can either follow the suggested (no D.I.) way, i.e.:
class ExampleViewModel : ViewModel() { /*...*/ }
#Composable
fun MyExample(
viewModel: ExampleViewModel = viewModel()
) {
// use viewModel here
}
or you could (and probably should) use a D.I. library such as Hilt or Koin.
I'm creating an app to communicate with an external device through bluetooth, the connection is with serial protocol (rfcomm). Fortunately I found a good lib on GitHub named BlueFlow written completely in Kotlin and coroutines. I want to implement the MVVM pattern suggested in the android dev portal but I can't figure which is the right role of the bluetooth.
I have a base activity and a fragment where I want to manage the ui components and I want to update the text fields of the ui using data binding.
I think I need to create a variable in the ViewModel of type LiveData and Observe it in the fragment for changes.
The bluetooth library has a singleton class that I instantiate in the ViewModel and I need to pass it a context. The bluetooth class has a function for read incoming data "readByteArray" and it returns a Flow<ByteArray>. I suppose this is the "Remote Data Source" in the MVVM architecture, am I right? Then I need to build a repository on top of it. Here there's the first stumbling block, how can I use the function readByteArray here? I can not use the singleton without pass a context and I think is not good to use context in this part of the architecture.
I also wrote a model class for the data received and it's like:
#Parcelize
data class IncomingResult(
#SerializedName("battery")
val battery: Int,
#SerializedName("sensor_one")
val sensorOne: Int,
#SerializedName("sensor_two")
val sensorTwo: Int,
): Parcelable
I need this class because sometimes I have to save these data into a room database.
I really appreciate any help/suggestion. I'm struggling with this problem from a week without find a solution. This is how I thought MVVM should be implemented in my project but I'm not sure it's correct:
Fragment
|
|
ViewModel
|
|
Repository
|
__________ | _________
| |
| |
Room Database Bluetooth
incoming data
You don't need LiveData everywhere, Only use it if you have to observe it or update the UI continuously like you want to use it in the variable when you have to take live data from the UI like editText. You can use liveData everywhere in your project, it is up to you whether you want to use it or not, I recommend that you have to look for the necessity when choosing it.
You are correct about the readByteArray as it is a source of data that we are using, so it is considered as a repository in MVVM.
In the case of MVP, the Presenter holds a view object. While in the case of MVVM, VM does not hold View object because view updated via data binding/live data. I want to know that if I use RxJava/Data binding in the case of MVP then no need to hold view object by the presenter. Now there is any diff in MVP and MVVM? Any valuable suggestions, please?
One clear diff I can see is that in the case of MVVM, VM holds data while activity recreated. While there is no such advantage in MVP.
https://medium.com/#prajvalprabhakar/mvp-vs-mvvm-93657494106b
https://www.vogella.com/tutorials/AndroidArchitecture/article.html
i think no if we use rx with mvp than we can say its reactive programing but not exactly mvvm becuase if we see mvvm arch. it's not only include reactive things or live data its also include data biniding and many more and yes main thing it's also use repository concepts for data call (API + local), thats why we can not say that mvp with rx its same as mvvm
I have an Android Studio project that is using an MVP architecture.
What is the advised packages structure for a project this style
we can do:
app:
screen_name
activityA
presenterA
interfaceA
or:
activities
activityA
activityB
preentors
presentorA
presentorB
etc
Your problem is just only UI part of MVP architectural pattern. Which is View classes along with their corresponding Presenters. And the better solution is the first approach.
App should have package according to features, NOT by the common functionality. We should group together the classes which are getting changed/modify together.
Some developers group source code by layer - like the second approach - because they want to keep the same package structure for ALL the projects they work on. But that is bad decision because it's always HARD to find classes when they are grouped only because they share same parent classes!
Ex: For activities, some developers put them in activity package because all activities extends Activity class. It makes sense because this is activity-ONLY package, BUT it is hard to go through those packages.
For more information, see: android-mvp-architecture and this S.O answer
In addition to the other answers i would recommend to look at android architecture blueprints, which may give you ideas of how to organize and implement your application.
MVP is good choice. You can follow following pattern:
app:
1. activities:
+ interface to represent view (i.e activity)
+ actual activity java class
2. Presenter:
+ interface to represents presenter
+ java class to represent presenter implementation
3. Model:
+ interface to represents model
+ java class to represent model implementation (do network calls here, pass callback to presenter which then gives data to activity)
I try to understand what the best way is to program a "clean" Android app. I found an interesting article about it where they use a kind of a 3 layer architecture.
Now I read that android uses the MVP design pattern and try to understand this. The way I understand the MVP principle (in the android context) is that:
the Model layer are the logic classes
the presenter are the classes that are "linked" to an XML (the activities)
the passive view are the XML's.
Is this correct?
When this is correct, is it then also correct that the 3 layer model fits perfectly in the MVP principle because:
the presentation layer from the 3 layer architecture fits in the presenter layer of MVP
The business and the data layer from the 3 layer architecture fits perfectly in the model part of the MVP?
I hope my questions are clear because it is a complicated topic for me.
Maybe this clears up my vision (way of thinking) about this...
first thing I wanted to clarify is that MVP or any other pattern for that matter is no specific of Android dev and, can be applied to any other framework.
I think you got the gist of it:
view is usually implemented by activities and fragments and will contain the reference to the presenter
the presenter is that middle man between the view and model. Retrieves data from the model and returns it already formatted to the view so it doesn't need to do anything else but display it.
the model can be seen in a simplistic way as the "data provider". It can be as complex as you want, using internal db, lots of clases etc.
If you are interested in Android apps architecture I suggest you watch this talk given at Android dev summit this year. It is one of the bests I've seen
https://www.youtube.com/watch?v=BlkJzgjzL0c
Even though this question has an answer, I don't think this answer is complete by any means.
MVP is a general concept which can have many various implementations, some of which differ substantially. Moreover, the concept itself is very ambiguous - different people can have different concepts in mind when they say MVP. One of the most widespread ones is shown in the below picture:
Regardless of implementation, the general definitions of MVP components are:
Model: abstraction of "application state storage". The definition of what the "state" is and how it is stored are implementation details. Model implementations should not have dependency on View or Presenter.
View: abstraction of "user interface". The definition of who the "user" is and how it interacts with the View are implementation details. View implementations should not have dependency on Model or Presenter.
Presenter: encapsulates application's business logic. Presenter processes user input events received from view, and alters application's state stored in model in response. Presenter also processes changes of application's state stored in model and updates view in response. Presenter usually depends on both the View and the Model.
If you need more information about MVP in context of Android development, you can find it in this post: MVP and MVC Architectural Patterns in Android
Important issues which need to be addressed while implementing MVP in android are activity leaks which cause memory leaks and app crashes due to background process updating closed activity.
Due to presenter having reference to activity, if presenter can't be garbage collected, activity will stay in memory.
Both of the issues can be solved by using life cycle methods of activity or fragment and releasing resources in those methods so that memory leaks and app crashes are prevented.
Cleaning up of resources related background work can be easily implemented using RXJava, for more information about MVP and MVP with RXJava, see http://www.zoftino.com/android-model-view-presenter-mvp-pattern-example
Here is simplest way to implement MVP pattern in your application android_mvp_login_sample
As you have come to know basics of Clean Architechure. The following example depicts how actual your MVP pattern is implemented.
Example:
interface BaseContract {
interface BaseView {
//Methods for View
void onDoSomething();
}
interface BasePresenter {
void doSomething();
}
}
class BaseMainPresenter implements BaseContract.BasePresenter {
BaseContract.BaseView view;
BaseMainPresenter(BaseContract.BaseView view) {
this.view = view;
}
#Override
public void doSomething() {
if (view != null)
view.onDoSomething();
}
}
class DemoClass implements BaseContract.BaseView {
//Create object of Presenter
/****
* Example :
* BaseMainPresenter baseMainPresenter = new BaseMainPresenter(this);
*/
#Override
public void onDoSomething() {
//Deal with Context here.
}
}
Refer below link for sample Actual implementation with scenario & learn more about Clean Architechure : https://github.com/android10/Android-CleanArchitecture
Here on github
https://github.com/saksham24/Android-Firebase-Mvp-Mvc-Mvvm-chat
i made a repo containing 3 applications with same functionality but written in 3 different android patterns(Mvc, Mvp, Mvvm)
Understanding three different pattern is quite easy if we get a simple good example on them so i made a repo to contribute my knowledge to this developer community.
Also the repository is written using proper java guidelines and conventions(including naming and packages, modules) so people looking for such project can also view this repository.
now
if you want to know the difference between android Mvp,Mvc, MvvM see this explanation by realm
https://academy.realm.io/posts/eric-maxwell-mvc-mvp-and-mvvm-on-android/
if you want to compare three pattern see this wonder full blog https://thinkmobiles.com/blog/mvp-vs-mvvm-android-patterns/
Now I read that android uses the MVP design pattern and try to
understand this. The way I understand the MVP principle (in the
android context) is that:
the Model layer are the logic classes
the presenter are the classes that are "linked" to an XML (the activities)
the passive view are the
XML's.
Is this correct?
Not fully: for the Model layer it is true, but for the Presenter it is not. The Presenter is not linked to XML although it has reference to the View through its constructor. The View is the Activity/Fragment in android.
You might want to check here for a sample MVP app for android.