Search⌘ K
AI Features

Working With ViewModels

Explore how to implement ViewModels in Android development to maintain UI-related data independently of activity or fragment lifecycles. Understand how ViewModels help preserve data during configuration changes such as screen rotations, ensuring a seamless user experience and simpler lifecycle management.

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