0Pricing
Android Academy · Lesson

Why Use a ViewModel?

Survive configuration changes cleanly.

Why Use a ViewModel? is a free Android Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is a ViewModel?

A ViewModel is an Android architecture component designed to store and manage UI-related data in a lifecycle-conscious way.

It survives configuration changes such as screen rotations, so your data does not get destroyed and recreated every time the system rebuilds the UI.

The Configuration Change Problem

When you rotate the device, Android destroys and recreates the Activity. Any state held inside the Activity or Composable is lost.

  • A counter resets to zero.
  • A loaded list disappears.
  • A network request might restart.

ViewModel solves this by living outside the Activity instance lifecycle.

How a ViewModel Survives

The framework keeps the same ViewModel instance alive across recreations. When the new Activity is created, it is handed the existing ViewModel rather than a fresh one.

class CounterViewModel : ViewModel() {
    var count = 0
        private set

    fun increment() {
        count++
    }
}

Obtaining a ViewModel in Compose

In Jetpack Compose you typically retrieve a ViewModel with the viewModel() helper. It returns the same instance for the lifecycle owner.

import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun CounterScreen(
    vm: CounterViewModel = viewModel()
) {
    Text("Count: " + vm.count)
}

Separation of Concerns

A ViewModel encourages a clean split:

  • UI layer (Composables/Activities) only renders state and forwards events.
  • ViewModel holds state and business logic.

This makes the UI thinner and the logic easier to test.

ViewModel Scope and Ownership

A ViewModel is scoped to a ViewModelStoreOwner, usually an Activity, Fragment, or navigation back stack entry.

It is cleared automatically when that owner is permanently destroyed, for example when the user finishes the Activity by pressing back.

The onCleared Callback

When the ViewModel is finally destroyed, the framework calls onCleared(). Use it to release resources you opened.

class MyViewModel : ViewModel() {
    override fun onCleared() {
        super.onCleared()
        // cancel jobs, close listeners
    }
}

What NOT to Put in a ViewModel

Never hold references to Views, Activities, or any Context tied to the UI inside a ViewModel. Because the ViewModel outlives the Activity, doing so causes memory leaks.

If you need an application context, use AndroidViewModel instead.

AndroidViewModel for App Context

When you genuinely need a Context, extend AndroidViewModel, which safely provides the long-lived application context.

class PrefsViewModel(
    app: Application
) : AndroidViewModel(app) {
    private val context = getApplication<Application>()
}

Passing Constructor Arguments

To inject dependencies (like a repository) into a ViewModel, use a ViewModelFactory or a DI framework such as Hilt. We cover Hilt later in this track.

class UserViewModel(
    private val repo: UserRepository
) : ViewModel() {
    // repo provided via a factory or Hilt
}

Why ViewModels Matter

ViewModels are a cornerstone of modern Android architecture. They give you:

  • Survival across configuration changes.
  • A clean separation between UI and logic.
  • Predictable, testable state management.

Quick Check

Test your understanding of why ViewModels are used.

Recap

You learned:

  • A ViewModel stores UI state and survives configuration changes.
  • It must never hold View or Activity references to avoid leaks.
  • It is scoped to an owner and cleared via onCleared().
  • AndroidViewModel provides a safe application Context.

Frequently asked questions

Is the “Why Use a ViewModel?” lesson free?

Yes — the full text of “Why Use a ViewModel?” is free to read here on the web, and the Android Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “Why Use a ViewModel?”?

Survive configuration changes cleanly. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Android Academy?

No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Why Use a ViewModel?” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Android Academy lesson?

Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why Use a ViewModel?
  2. Exposing State from ViewModel
  3. The Android Lifecycle
  4. collectAsStateWithLifecycle
← Back to Android Academy