At Google I/O last year, Google announced Android Architecture Components. This “Jetpack” suite of libraries gives developers an easier way to build apps. It’s flagship offerings,
LiveData, can be used in almost any app. Plus, now that Google is now pushing MVVM architecture, these libraries are a perfect fit. Let’s see how we can get started with
See the YouTube video tutorial for this article to learn about Android Architecture Components in video form. Have questions? Leave them in the YouTube comments and I’ll try to answer as many as I can!
First, we need to set up our Android Studio project. Next, we need to add our dependencies to the Module
build.gradle file. Ensure that these 4 lines of code are at the top of your
After adding the
kotlin-kapt plugin, add this 1 line to the same
build.gradle file. We need
android.arch.lifecycle:extensions:1.1.1, which is currently on version 1.1.1. If Android Studio highlights that line, hover your mouse over that line and Android Studio will display the latest version (for example: 1.2.6, 2.4.9, etc.).
After syncing Gradle, it’s time to create our
ViewModel class that will compliment
MainViewModel class will extend
ViewModel and contain
MainViewModel class, written in Kotlin, is smart. It know when it’s not longer needed. For example, if a user navigates to a new screen that doesn’t need
MainViewModel any more, Android will automatically recycle
MainViewModel. You don’t have to worry about
To set up the layout, open Text mode and copy and paste the following code into
Last, but not least, we need to finish setting up
MainActivity.kt. Copy and paste the code below into
On line 17, we get a reference to the
MainViewModel. This is how
MainActivity is linked to
MainViewModel. On line 19-21, we listen, or
Observe, for changes.
From line 23-25, we setup an
OnClickListener to listen for clicks on submitButton. Whenever there is a click on submitButton, we call
viewModel.fullName.value and set it to
That’s all! Hopefully you learned something. If you have any questions, please leave them below. Thanks!