Android Architecture Components Tutorial: ViewModel + LiveData

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, ViewModel and 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 ViewModel and LiveData!

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 build.gradle file.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

// start your build.gradle file with these 4 lines

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.).

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    // add this line:
    implementation "android.arch.lifecycle:extensions:1.1.1"
}
Add the plugin, dependency, then sync Gradle.

After syncing Gradle, it’s time to create our ViewModel class that will compliment MainActivity. The MainViewModel class will extend ViewModel and contain LiveData / MutableLiveData variables.

package com.example.componentstest

import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel

class MainViewModel : ViewModel() {

    val fullName = MutableLiveData<String>()
}

The 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 NullPointerException‘s.

Open content_main.xml and select Text to enter “manual” mode.

To set up the layout, open Text mode and copy and paste the following code into content_main.xml.

Last, but not least, we need to finish setting up MainActivity.kt. Copy and paste the code below into MainActivity.kt.

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 firstNameField.text.toString().

That’s all! Hopefully you learned something. If you have any questions, please leave them below. Thanks!

Daniel Malone Daniel Malone
Bringing more than a decade of software engineering experience, Daniel Malone is Editor at androidEveryday. An Austin native, Daniel is often found reading technical books, blogging and creating YouTube tutorials. When not working, he likes to listen to pop hits on Google Play Music.

Android RecyclerView Tutorial (Part 1)

  • Most apps contain lists of data using RecyclerView.
  • In this tutorial, use ConstraintLayout and Kotlin to display a list of data.

1 year ago

findViewById() in Kotlin

  • As you may have discovered, findViewByid() is no longer needed.
  • Kotlin adds the ability to directly access Views.

1 year ago

Android SharedPreferences Tutorial in Kotlin

  • Use SharedPreferences to store simple data in Android Studio projects.
  • It's good for storing small amounts of data

    1 year ago

Cleaner Architecture for Android Apps

  • Clean Architecture for Android can help developers prepare for change.
  • But app developers can't possibly know what will change.

    1 year ago

Android RecyclerView with Kotlin – Part 3

  • In part three of this series, finish creating the RecyclerView.
  • Use onBindViewHolder to display data.

1 year ago

Android RecyclerView with Kotlin – Part 2

  • Create the entire RecylerView for our UsersAdapter.
  • Continued from part 1, where we set up the Android Studio project.

1 year ago

Android and RxJava: Using a Single

  • Use RxJava's Single class when the expected type is either a success or error.
  • It's only slightly different from Observable.just(), which we discussed in the last article.

1 year ago

Android and RxJava: Getting Started

  • The powerful library RxJava can help developers build better apps.
  • See how to use Observables and Observers in this tutorial.

1 year ago

Android RecyclerView with Kotlin - Part 1

  • Oftentimes, developers need to display a list of some sort of data.
  • Whatever type of data is displayed, you should use a RecyclerView.

1 year ago

Display Sample Data when Creating a RecyclerView

  • Android Studio's default RecyclerView preview lacks sample data.
  • Adding sample data can be helpful for debugging.

1 year ago

Android Studio Tutorial with Kotlin (2018 Edition) - Part 2

  • Create a UI in Android Studio using the Design mode.
  • In this latest installment for beginners, we'll add a widget to our screen.

1 year ago