Get a Quote


Choose Android MVVM over MVP Architecture

oneclick, administrator/ February 25, 2019 10:41 am 431 Views

Android architecture - MVVM

1) Overview

“Well begun is half done”. This small sentances tell us a lot. So good start is very important  for achieve success or any of the good finish work. If you are android developer and wants to develop good application you should be follow good android architecture. There are many android architecture, but which one is best for our application? We will clear out your all doubts .

Before we start about MVVM we will discuss about some key points and why MVVM? Day to day technology is growing faster and try to make our life easier. Now a days Android is very famous mobile operating system developed by Google.

For keep  scalability,easy to maintain,easy to test,clean code you have to follow good architecture. Android provide many Architecture from starting onwards. Following are architecture patterns,

1.1) MVC(Model View Controler)
1.2) MVP(Model View Presenter)
1.3) MVVM(Model View ViewModel)

For making android app you have to follow any one of them, but for good quality of the product at the end, you have to choose better one. We will describe all pattern one by one in brief and detail about MVVM.

1.1) MVC

In short we can say MVC is the default pattern where an Activity acts as a controller and XML files are view.

MVC pattern

• Model – is the data layer, responsible for managing the business logic and handling network or database API.
• View –  is the UI layer which is a showing data from the Model.
• Controller – is the contain all the logic and gets notified by user action and updates the Model as needed.

At the initial time of android development we used mvc but because of increase complexity,inefficiency of data access in view and difficulty of using this pattern in modern UI, android found new architecture is MVP.

1.2) MVP

The MVP pattern allows separating the presentation layer from the logic and the presenter knows about the view and view knows about the presenter. They interact with each other through an interface.

MVP pattern

• Model – is the data layer, responsible for managing the business logic and handling network or database API.
• View –  is the UI(Activity,fragment etc) layer working same as like in MVC. View will contain a reference to the presenter.
• Presenter – is responsible to act as the mediator between view and model. It retrieves data from the model and provide it to the view.

MVP pattern is good for achieving clean code and you can do asynchronous call via interface. This is greate for testing and modularization. In MVP view is dumb and presenter almost take care about everything so it will become complicated and it may produce more classess and java code. In MVP the relationship between view and presenter is one to one.

1.3) MVVM

MVVM pattern

• Model – is contain logic part which related with the data of our application. Like POJO,database,network api etc
• View –  is like same as other architecture, which is layout of screen which contain widgets and lots of other views.
• ViewModel – is the main part of this architecture. It work as link between other two module. It is provide data from model to view and always provide callbacks to view for update the status. We can also call as it`s an object which is define the behavior of View.

Important thing In MVVM are
• The view has knowledge about the view-model and  view-model doesn’t no anything about the view
• Activities and XML`s are behave as views, and in ViewModel, you can write your business logic. So UI is separated from business logic.

Finally, we can say that the concept of MVVM is to separate presentation logic from business logic Which will give us a big result.

2) Why MVVM?

There are many benifits of MVVM. Let’s see one by one.

• This is newly introduced architecture and It`s contain component like LiveData which is an observable data holder.

• LiveData is lifecycle-aware. means ViewModel retained across the lifecycle of the activity.

• data-change <-> UI change cycle works with LiveData.

• Room is data base library which is persistence library of SQLite, introduce as a part of Android Architecture, which is support LiveData.

• LiveData objects is able to observe for changes without creating explicit and rigid dependency paths between them.

• Viewmodel automatically having their holding data retained during configuration changes.

In MVVM, main part is Viewmodel, which is handling your almost bussiness logic using livedata and no more interface or other  dependency requiered.  Using all the above features we can achive following result:

• Make unit testing easier
• Clean code structure of application
• Developement flexibility
• Seperation of logic

3) Components

As we discuss previously about MVVM, there are main three components of MVVM archtecture. Binder is also important part of this strcture which is very helpfull for binding and synchronize of viewmodel and view with each other.

Model – is act as a data layer which represents the state content. It holds the information. The key point to remember here is model keep always clean. The room is the database for storing the data and it is persistence library which is able to use live data.

View – is your activity, fragment or any other class which represents the widgets. Using data binding view is forward the callback of the user’s interaction to the ViewModel. Here data binding is a link between view and viewmodel. In MVVM, ViewModel reduces the work of view, means now you have to write your all the logic into ViewModel.

View model – is state of the data which is stored into the model.viewmodel has a binder for communication between view and model. This automated binding functionality is to kept MVVM to unique from other architecture like MVP and MVC.

Binder – is mark up language which makes developer job easy. Using other architecture you have to write more boilerplate code, but the binder is reduced this logic to synchronize the between view and ViewModel.

Livedata – is the component which is helpfull to remove view dependency. It is an observable data holder class which aware of lifecycle.

4) Data binding

Using Data binding we can reduce our lots of boiler plate syntex and unrelated binding code like we are using findviewbyid. We can say No more findViewByIds in MVVM using data binding. This is support two-way data binding. Rather than programmatically you can bind your data with UI elements into your layouts. Let see how to use binding in next point with full code example.

5) Steps to implementation(How to use MVVM)

Using one small example of code we will implement MVVM architecture. Using email and password we will do login through Web API. For that we have to follow some basic steps given below.

5.1) Create new project
First of all create new android project name “MvvmDemo” and give package name “com.mvvm_demo”.

5.2) Enabling DataBinding
Befor you start you have to enable the data binding using  below syntext into your app level build.gradle file inside android tag.

android{
dataBinding {
enabled = true
}
.
.
.
}

5.3) Make model class

Now make pojo class for login data as VoLoginData.java

public class VoLoginData {
private String success;
private String message;
private String status_code;

public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus_code() {
return status_code;
}
public void setStatus_code(String status_code) {
this.status_code = status_code;
}

}

5.4) integrat data binding in xml layout

To enable binding function into layout, you have to add <layout> tag to the root element of your layout, and for setup data you have to add <data> tag and <variable> tags. Finally your layout look like as below

activity_main.xml
<layout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
xmlns:tools=”http://schemas.android.com/tools”>
<data>
<variable
name=”loginViewModel”
type=”com.mvvm_demo.viewModels.LoginViewModel” />
</data>

<LinearLayout
android:id=”@+id/activity_main_ll_main”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_centerVertical=”true”
android:layout_gravity=”center”
android:gravity=”center”
android:orientation=”vertical”>

<android.support.design.widget.TextInputLayout
android:id=”@+id/activity_login_input_email”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>
<android.support.design.widget.TextInputEditText
android:id=”@+id/activity_main_tie_email”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:layout_margin=”10dp”
android:gravity=”center”
android:hint=”email”
android:inputType=”textEmailAddress”
android:maxLines=”1″
android:padding=”7dp”
android:singleLine=”true”
android:text=”@={loginViewModel.strUsreName}”
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id=”@+id/activity_main_input_password”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>
<android.support.design.widget.TextInputEditText
android:id=”@+id/activity_login_tie_password”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_margin=”10dp”
android:gravity=”center”
android:hint=”password”
android:inputType=”textPassword”
android:maxLines=”1″
android:padding=”7dp”
android:singleLine=”true”
android:text=”@={loginViewModel.strPassword}”
/>
</android.support.design.widget.TextInputLayout>
<TextView
android:id=”@+id/activity_login_screen_txt_login”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:gravity=”center”
android:padding=”8dp”
android:onClick=”@{(v) -> loginViewModel.onClickLogin()}”
android:text=”@string/login”/>

</LinearLayout>
</layout>

5.5) Initialize binding object into activity(view)

There is some naming convention rules for binding data to layout. If your xml layout name is activity_main.xml where you enable data binding, the binding class name will be ActivityMainBinding. First and after “_”(slash) first later should be Capital, “_”(slash) will be remove and Binding suffix will be added in last.

Now in oncreate method  of your activity, syntext of binding class will be as below.

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

5.6) Make ViewModel class

Now once you complete binding, next you have to craete ViewModel class for setup data to xml and here ViewModel is mediator between view and model.

public class LoginViewModel extends ViewModel {

public MutableLiveData<String> strPassword = new MutableLiveData<>();
public MutableLiveData<String> strUsreName = new MutableLiveData<>();

private MutableLiveData<VoLoginData> userMutableLiveData;

public LoginViewModel() {
}

public LiveData<VoLoginData> () {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData;
}

public void onClickLogin() {

showWait();
Map<String, String> mHashMap = new HashMap<>();
mHashMap.put(“email”, strUsreName.getValue());
mHashMap.put(“password”, strPassword.getValue());

YourServiceClassHere.userLogin(mHashMap, new MyService.ServiceCallback<VoLoginData>() {
@Override
public void onSuccess(VoLoginData mVoRegister) {

removeWait();
onResponseSuccess(mVoRegister);

}
@Override
public void onError(Exception networkError) {
removeWait();
onResponseSuccess(null);

}
});

}

private void onResponseSuccess(VoLoginData mVoLoginResponses) {
userMutableLiveData.setValue(mVoLoginResponses);
}

public VoLoginData getLoginData() {
return userMutableLiveData.getValue();
}
}

5.7) Initialize ViewModel into your activity class

After creat ViewModel class initialize it into activity class and do all the logic task there, and in the activity just show the result into UI. You can find the implementation of viewmodel in below class.

ActivityMain.java

public class ActivityMain extends BaseActivity {

LoginViewModel mLoginViewModel;
ActivityMainBinding mActivityMainBinding;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

mActivityMainBinding.setLoginViewModel(mLoginViewModel);
mActivityMainBinding.setLifecycleOwner(this);

mLoginViewModel.getUser().observe(this, new Observer<VoLoginData>() {
@Override
public void onChanged(@Nullable VoLoginData mVoLoginResponse) {
if (mVoLoginResponse != null) {
if (mVoLoginResponse.getSuccess() != null && mVoLoginResponse.getSuccess().equalsIgnoreCase(“1″)) {
//you will be notify here from viewmodel class while you get response from service
//do whatever you want
}
}
}
});

}

}

While you set the ViewModel into binding object you have to remember some naming conventions, Like first letter is capital of variable name after using “mActivityMainBinding.set”
Like, mActivityMainBinding.setLoginViewModel(mLoginViewModel);

In this syntext “setLoginViewModel” is the name of variable define into xml inside data tag,
<data>
<variable
name=”loginViewModel”

Here we call login api into view model, we take onclick event into xml, using reference of viewmodel. Once we get the result from service we set it into (here userMutableLiveData is object of LiveData) MutableLiveData. Now this observable LiveData notify to our activity where we implement it(mLoginViewModel.getUser().observe()).

Now you can imagine how easy it’s. You will not find any findviewbyid or any boiler plate code into activity or viewmodel.

6) Compare with other architecture

After discussed all the points we can clearly say that, MVP is using interface for communication between presenter and view, while MVVM is using observer for communication between ViewModel and view.

In MVVM View not requiered to request every time to the ViewModel for latest data, using LiveData observer View register itself and that Viewmodel keep reference of particular LiveData, now in this scenario if anything is change into Model data, ViewModel get update and View get  notifying of this change automatic.

7) Benefit & Drawback of  MVVM

Benefits

– MVVM is resolved issue of tight coupling which is facing in MVP(One-to-One), In the MVVM(One-to-Many) View keep reference to ViewModel and ViewModel dont have any knowledge about View.

– For testability in the presenter slightly hard because of dependancy of a view, while in ViewModel its very easy to do unit testing, because of there is no dependancy of View.

– In the second module(Why mvvm?) we cover almost all the advantages of LiveData and ViewModel for MVVM

Drawback

– For simple UI no need to implement ViewModel and everything

– Same way for bigger project also it may be hard to design ViewModel

– In case of complex data binding debugging would be hard

8) Conclusion

MVP and MVVM both are better than MVC because of both are make our application clean and modularise. For very simple application you can use MVC, and using data binding with MVVM it makes attractive, less code and good programming technique.

If you would like to use interface MVP is good pattern. So it’s depend on you that which architecture you want to follow, and which one is best for your application and in which pattern you are good.

If you ask me out of two which is best? My opinion is try to use MVVM.

We, ”OneClick”, also develop applications using MVVM and in next blog we are going to implement “Clean Code Architecture”. It’s great feedback from our users after using MVVM. If you are looking for MVVM architect development for your existing or new application development work Contact us. We would love to assist you.

Thank you for reading. Have a good day.