Design Pattern

MVC (Model View Controller)

1. You open the refrigerator 2. You get water bottle 3. You pay

Model: Bottle View: You Controller: You

Example: https://github.com/laetuz/MVC-DEMO-ANDROID

MVP (Model View Presenter)

1. You request the water 2. Waiter will go to refrigerator 3. You pay and you get the water bottle

Model: Bottle View: You Presenter: The Waiter

Example: https://github.com/laetuz/MVP-DEMO

MVVM (Model View View-Model)

1. You insert the coin 2. You request the water 3. Machine will release the bottle

Model: Bottle View: You View-Model: “BINDING”

How to implement:

  1. We need to make the connection “Binding” - “ViewModel”
  1. Implement the ViewModel dependency. Grab it Here.
  1. Create the ViewModel Class.
  1. Extends the class to the ViewModel.
public class AppViewModel extends ViewModel {
  1. Connect ViewModel with Model(Or Database in most projects).
private Model getAppFromDatabase(){
        return new Model("MVVM DEMO",233,5);
    }
  1. Request LiveData by inputting these codes into ViewModel Class:
MutableLiveData<String> mutableLiveData;
  1. Connecting ViewModel with MainActivity (View).
public void getAppName(){
        String appName = getAppFromDatabase().getAppName();
        mutableLiveData.setValue(appName);
    }
  1. Connecting MainActivity with ViewModel and listening to LiveData, in MainActivity
AppViewModel appViewModel;
  1. Inside the Oncreate, add new ViewModelProvider
appViewModel = new ViewModelProvider(this).get(AppViewModel.class);
  1. Still inside the OnCreate, Listening and observing the changes to LiveData
appViewModel.mutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                textView.setText(s);
            }
  1. Go to AppViewModel.java and we can edit, add data now if we change the code of MutableLiveData to
MutableLiveData<String> mutableLiveData = new MutableLiveData<>();
  1. Final Result

Source Code: https://github.com/laetuz/MVVM-DEMO-ANDROID-JAVA

Reference:

MVVM on Kotlin:

MVVM on Android Crash Course - Kotlin & Android Architecture Components - Reso Coder
Model - View - ViewModel is an architectural pattern which will empower you to write manageable, maintainable, cleaner and testable code. MVVM is also supported and encouraged by Google itself. There are many first-party libraries like lifecycle-aware components, LiveData, ViewModel and many more. In the previous post, you learned the theory behind MVVM.
https://resocoder.com/2018/09/07/mvvm-on-android-crash-course-kotlin-android-architecture-components/