Working With ViewModels

Learn how to efficiently manage UI-related data by decoupling its lifecycle from Android activities and fragments.

Introduction

The ViewModel class is one of the Android architectural components that let us manage UI-related data independent of the Android UI controller (activities or fragments) lifecycle. An activity or a fragment can undergo several lifecycle changes, which might inadvertently affect the UI data. For example, when the device screen is rotated, the activity is destroyed and recreated. In such a scenario, any associated UI-related data would be lost.

ViewModel lets us separate the UI data from the activity/fragment lifecycle and allows the data to persist across configuration changes. In this lesson, we’ll learn how to use a ViewModel through a simple example.

Let’s go ahead and learn how to use a ViewModel.

Add library dependencies

To use the ViewModel lifecycle component in our app, we first need to add the following dependencies in our app/build.gradle file:

Get hands-on with 1200+ tech skills courses.