Introduction to Android App Development With Kotlin: MVVM Architecture (Part 6) – DZone Java | xxxIntroduction to Android App Development With Kotlin: MVVM Architecture (Part 6) – DZone Java – xxx
菜单

Introduction to Android App Development With Kotlin: MVVM Architecture (Part 6) – DZone Java

二月 28, 2019 - MorningStar

Over a million developers have joined DZone.
Introduction to Android App Development With Kotlin: MVVM Architecture (Part 6) - DZone Java

{{announcement.body}}

{{announcement.title}}

Let’s be friends:

Introduction to Android App Development With Kotlin: MVVM Architecture (Part 6)

DZone’s Guide to

Introduction to Android App Development With Kotlin: MVVM Architecture (Part 6)

Learn more about architectural patterns for Android app development.

Mar. 25, 19 · Java Zone ·

Free Resource

Join the DZone community and get the full member experience.

Join For Free

Get the Edge with a Professional Java IDE. 30-day free trial.

Having the inputs in our app validated along with some basic navigation working, it’s time to mention the architecture. There are multiple architectural patterns you can apply to your app, e.g. MVC (Model-View-Controller), MVVM (Model-View-ViewModel), and MVI (Model-View-Intent). Feel free to research all of them, but make sure you end up using at least one. The worst thing you can do is to follow none, which will more than likely result in a messy state of your repository. MVVM is the subject of todays lesson and that’s the pattern we will apply in our app. I’ve been using MVVM (Model-View-View Model) in my projects and I think it provides a very nice and clean separation of concerns.

Lesson 6

What Is MVVM?

MVVM consists of three parts:

  1. View — what’s displayed on users screen. Allows for interaction.
  2. ViewModel — bridge between the view and model. Exposes business logic relevant to a specific view.
  3. Model — deals with application data e.g. Network interface (API), SQLite database access. Responsible for storing and fetching of data

Why Should I Use MVVM?

The benefits of using this pattern include:

  1. Clean separation of concerns (decoupled codebase)
  2. Results in easily testable code.
  3. Allows for rapid design change.
  4.  ViewModels are Lifecycle aware.

Example

class MyViewModel(application: Application) : AndroidViewModel(application) {     private lateinit var users: MutableLiveData<List<User>>      fun getUsers(): MutableLiveData<List<User>> {          if (!::users.isInitialized) {             users = MutableLiveData()             loadUsers()         }          return users     }      private fun loadUsers() {         // Asynchronous operation to fetch users.     } } 

MyViewModel extends AndroidViewModel class. It contains a class variable users of type MutableLiveData<List<User>>>MutableLiveData and LiveDataobjects will be discussed in one of the next tutorials, so don’t worry about them for now.

We will then need to get access to the ViewModel in our Fragment. This is how you achieve it

override fun onCreate(savedInstanceState: Bundle?) {     super.onCreate(savedInstanceState)      // Create a ViewModel the first time the system calls an activity's onCreate() method.     // Re-created activities receive the same MyViewModel instance created by the first activity.     val model = ViewModelProviders.of(this).get(MyViewModel::class.java)     model.getUsers().observe(this, Observer<List<User>>{ users ->         // update UI     })  }

How Do I Implement MVVM?

Hopefully, from looking at the above example, you’ll have a general idea of what’s required to implement our very own ViewModel.Let’s go through it step by step.

Step 1.

Import the following in you build.gradle file

implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"

Step 2.

Create a new Kotlin class and name it  NewMovieViewModel

Step 3.

 NewMovieViewModel  must extend AndroidViewModel(application) 

class NewMovieViewModel(application: Application): AndroidViewModel(application) {  }

Step 4.

Get an instance of your brand new ViewModel in the NewMovieFragment inside the onCreate.

override fun onCreate(savedInstanceState: Bundle?) {     super.onCreate(savedInstanceState)      // Create a ViewModel the first time the system calls an activity's onCreate() method.     // Re-created activities receive the same MyViewModel instance created by the first activity.      val model = ViewModelProviders.of(this).get(NewMovieViewModel::class.java)   }

Voila. You have successfully created and instantiated a ViewModel. Compile and run the app to make sure everything works. Naturally, this ViewModel doesn’t do very much yet, but that will change once we create our first database.

Conclusion

You now understand the importance of following an architectural pattern when developing an Android app and you know how to implement the  ViewModel in MVVM Architecture.

If you have followed the steps above you have successfully created your first ViewModel. This ViewModel will serve as access point to the Model of our app. In the case of our app, our model will be a SQLite database that will be managed by Room and an Androids wrapper around SQLite that makes creating and managing databases a breeze. We will learn more about Room in the next tutorial.

Stay tuned!

Complete working code can be found in my GitHub account here.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
android development ,kotlin 1.3 ,mvvm ,app development ,java ,anroid ,kotlin

Opinions expressed by DZone contributors are their own.

Java Partner Resources

Red Hat Developer Program

Red Hat Developer Program

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.linkDescription }}

{{ parent.urlSource.name }}

· {{ parent.articleDate | date:’MMM. dd, yyyy’ }} {{ parent.linkDate | date:’MMM. dd, yyyy’ }}



Notice: Undefined variable: canUpdate in /var/www/html/wordpress/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 51