By Shakil Ahmed, Android developer & software engineer
ViewModel in Jetpack Compose: Add Search and Favorites
Stop losing data when the phone rotates. Learn what a ViewModel is in plain English and add a search box and favorites to our fruit app.
Welcome back! In Part 8: Navigation Between Screens, our fruit app got two screens. Today we learn the Jetpack Compose ViewModel. A ViewModel is a safe place to keep your app's data. We will add a search box and a ❤️ favorite button to our fruit list, and all of that data will live inside a ViewModel. Don't worry, we go step by step.
The Problem: State Inside a Composable Gets Lost
In Part 6 we used remember { mutableStateOf(...) } to keep data like a counter. That works, but it has two problems.
Problem 1: Rotation. Turn your phone sideways and Android rebuilds the whole screen. Everything you stored with plain remember is gone. Your search text disappears. Your favorites disappear. Not nice!
Problem 2: Messy code. When one screen holds the data, the search logic and the favorite logic all sit inside your UI code. The screen gets long and confusing, and other screens can't use that data easily.
Tip:
rememberSaveablecan survive rotation for small values. But for real app data (lists, search, favorites), Android developers use a ViewModel.
What Is a ViewModel? (Plain-English Version)
Think of a restaurant.
- The waiter is your screen (the composable). The waiter shows things to the customer and takes their orders.
- The kitchen is the ViewModel. The kitchen keeps the food (data) and does the real work.
If the waiter goes home and a new waiter comes in, the kitchen is still there with all the food. In the same way, when you rotate your phone, the screen is rebuilt, but the ViewModel stays alive and keeps your data safe.
So the rule is simple:
- The ViewModel holds the data and the logic.
- The screen only shows the data and tells the ViewModel when the user does something.
Step 1: Add the Dependencies
Open app/build.gradle.kts (the one inside the app folder). Find the dependencies { } block where you added Navigation in Part 8. Add these two lines:
dependencies {
// ... your existing lines ...
implementation("androidx.navigation:navigation-compose:2.9.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
}
Click Sync Now at the top of the editor.
Let's understand it:
lifecycle-viewmodel-composegives us theViewModelclass and theviewModel()function for Compose.lifecycle-runtime-composegives uscollectAsStateWithLifecycle(), which lets the screen read data from the ViewModel safely.
Tip: Android Studio may show a yellow line and offer a newer version. That's fine. You can accept it. Version 2.11.0 was the latest stable version when I wrote this.
Step 2: Create the UI State
First, we describe everything our list screen needs in one small box. Create a new Kotlin file called FruitViewModel.kt (right-click your package → New → Kotlin Class/File). Add this:
data class FruitUiState(
val query: String = "",
val fruits: List<Fruit> = emptyList(),
val favorites: Set<String> = emptySet()
)
Let's understand it:
queryis the text the user typed in the search box.fruitsis the list we show on screen (already filtered by the search).favoritesis aSetof fruit names the user loved. ASetis like a list, but it never holds the same item twice. Perfect for favorites!- Each value has a default (
"",emptyList(),emptySet()), so we can create an empty state easily.
Step 3: Create the FruitViewModel
In the same file, below FruitUiState, add the ViewModel:
class FruitViewModel : ViewModel() {
private val _uiState = MutableStateFlow(FruitUiState(fruits = fruits))
val uiState: StateFlow<FruitUiState> = _uiState.asStateFlow()
fun onQueryChange(newQuery: String) {
_uiState.update { current ->
current.copy(
query = newQuery,
fruits = fruits.filter { it.name.contains(newQuery, ignoreCase = true) }
)
}
}
fun toggleFavorite(fruitName: String) {
_uiState.update { current ->
val newFavorites = if (fruitName in current.favorites) {
current.favorites - fruitName
} else {
current.favorites + fruitName
}
current.copy(favorites = newFavorites)
}
}
}
Press Alt+Enter on each red word to import it. These are the imports you need:
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
Let's understand it:
class FruitViewModel : ViewModel()means our class is a ViewModel, so Android keeps it alive during rotation.fruitsis the full list from Part 7. It is our "warehouse". The ViewModel decides which fruits to show.MutableStateFlowis a box that holds one value and tells everyone when the value changes. Only the ViewModel can change it, so we keep itprivate(the_in the name is a common habit for private versions).uiStateis a read-only version for the screen. The screen can look, but not touch.onQueryChangesaves the new search text and filters the list.ignoreCase = truemeans "man" finds "Mango".toggleFavoriteadds the name if it is not there, or removes it if it is there. Like a light switch.update { current -> current.copy(...) }takes the old state, makes a copy with a few changes, and saves it. We never change the old state directly.
Step 4: Update FruitRow With a ❤️ Button
Open the file with your FruitRow from Part 7 and replace it with this version:
@Composable
fun FruitRow(
fruit: Fruit,
isFavorite: Boolean,
onClick: () -> Unit,
onFavoriteClick: () -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.clickable { onClick() }
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = fruit.emoji, fontSize = 32.sp)
Spacer(modifier = Modifier.width(16.dp))
Column(modifier = Modifier.weight(1f)) {
Text(text = fruit.name, style = MaterialTheme.typography.titleMedium)
Text(text = "৳${fruit.price} per kg", style = MaterialTheme.typography.bodyMedium)
}
IconButton(onClick = onFavoriteClick) {
Text(text = if (isFavorite) "❤️" else "🤍", fontSize = 24.sp)
}
}
}
}
Let's understand it:
- Two new parameters:
isFavorite(should the heart be red?) andonFavoriteClick(what to do when the heart is tapped). Modifier.weight(1f)makes the name column take all free space, so the heart sits on the far right.IconButtonis a small round button. Inside, we show ❤️ or 🤍 depending onisFavorite.- Notice:
FruitRowdoes not change any data. It only says "hey, someone tapped the heart!"
Step 5: Update FruitListScreen With a Search Box
Replace your FruitListScreen with this:
@Composable
fun FruitListScreen(
uiState: FruitUiState,
onQueryChange: (String) -> Unit,
onFavoriteClick: (String) -> Unit,
onFruitClick: (String) -> Unit
) {
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
OutlinedTextField(
value = uiState.query,
onValueChange = onQueryChange,
label = { Text("Search fruits") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(12.dp))
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(uiState.fruits, key = { it.name }) { fruit ->
FruitRow(
fruit = fruit,
isFavorite = fruit.name in uiState.favorites,
onClick = { onFruitClick(fruit.name) },
onFavoriteClick = { onFavoriteClick(fruit.name) }
)
}
}
}
}
Let's understand it:
- The screen receives
uiState(the data) and three functions (the events). OutlinedTextFieldis a text box with a border. It showsuiState.queryand callsonQueryChangeon every key press.items(uiState.fruits, ...)now shows the filtered list, not the full list.fruit.name in uiState.favoriteschecks if this fruit is a favorite.
Tip: If
itemsstays red, importandroidx.compose.foundation.lazy.items(not the other options).
Step 6: Connect Everything in FruitApp
Now we create the ViewModel and give its data to the screen. Update FruitApp from Part 8:
@Composable
fun FruitApp(
modifier: Modifier = Modifier,
fruitViewModel: FruitViewModel = viewModel()
) {
val navController = rememberNavController()
val uiState by fruitViewModel.uiState.collectAsStateWithLifecycle()
NavHost(
navController = navController,
startDestination = "home",
modifier = modifier
) {
composable("home") {
FruitListScreen(
uiState = uiState,
onQueryChange = { fruitViewModel.onQueryChange(it) },
onFavoriteClick = { fruitViewModel.toggleFavorite(it) },
onFruitClick = { name -> navController.navigate("details/$name") }
)
}
composable("details/{fruitName}") { backStackEntry ->
val fruitName = backStackEntry.arguments?.getString("fruitName") ?: ""
FruitDetailsScreen(
fruitName = fruitName,
onBack = { navController.popBackStack() }
)
}
}
}
And in MainActivity, pass the padding to FruitApp:
setContent {
MyFirstAppTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
FruitApp(modifier = Modifier.padding(innerPadding))
}
}
}
The tricky imports for this step are:
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
Let's understand it:
viewModel()gives us aFruitViewModel. If one already exists, Android gives back the same one. That's how it survives rotation.- We create the ViewModel at the top, in
FruitApp. In the next part, more screens will share it. collectAsStateWithLifecycle()turns theStateFlowinto Compose state. When the data changes, the screen redraws by itself. It also stops listening when the app is in the background, which saves battery.by(with thegetValueimport) lets us writeuiStateinstead ofuiState.value.
Run the app. Type "an" in the search box: you'll see Mango, Banana, Orange, Pineapple. Tap a few hearts. Now rotate the phone (or the emulator). Your search and your hearts are still there! 🎉
State Flows Down, Events Flow Up
This is the most important idea in this lesson:
- State flows down:
FruitViewModel→FruitApp→FruitListScreen→FruitRow. Data goes down like water. - Events flow up:
FruitRowsays "heart tapped" →FruitListScreen→FruitApp→fruitViewModel.toggleFavorite(). Messages go up.
Only the ViewModel changes the data. Screens just show it and report clicks. This makes bugs easy to find, because there is only one place where data changes. Want to go deeper? Read my advanced guide on Jetpack Compose state management.
Common Errors
Unresolved reference: viewModel: You forgot thelifecycle-viewmodel-composedependency, or you didn't click Sync Now.collectAsStateWithLifecycleis red: Addlifecycle-runtime-composeand importandroidx.lifecycle.compose.collectAsStateWithLifecycle.- Error on
by: Importandroidx.compose.runtime.getValue. - Gradle sync fails asking for a newer
compileSdk: Click the suggested fix, or use the version Android Studio recommends.
Try It Yourself
- Add a "Clear" button next to the search box that calls
onQueryChange(""). - Show a counter above the list:
"${uiState.favorites.size} favorites". - Show the text "No fruits found 😢" when
uiState.fruitsis empty.
Frequently Asked Questions
Is a ViewModel saved forever, even after I close the app? No. A ViewModel survives rotation and screen changes, but it is cleared when the user fully closes the app. To save data forever, you need a database, which we'll learn later.
Why use StateFlow and not just mutableStateOf in the ViewModel?
Both can work. StateFlow is plain Kotlin, so it also works outside Compose, and it is what most Android teams use. Learning it now will help you later with coroutines.
Can I create a ViewModel with FruitViewModel() directly?
Please don't. If you write FruitViewModel(), you get a brand-new one every time, and it won't survive rotation. Always use viewModel().
Quick Recap
- State inside a composable can be lost on rotation and makes screens messy.
- A ViewModel is like a kitchen: it keeps data safe while the screen is rebuilt.
- We added
lifecycle-viewmodel-composeandlifecycle-runtime-compose. FruitUiStateholds the query, the filtered fruits and the favorites.StateFlow+collectAsStateWithLifecycle()connects the ViewModel to the screen.- State flows down, events flow up.
Next, we give our app a real top bar and bottom tabs, including a Favorites tab!
Related articles
Pick a photo, read its text on-device with ML Kit Text Recognition v2, and show blocks and lines in Jetpack Compose with a copy button.
Run AI directly on the phone with Gemini Nano and ML Kit GenAI APIs: privacy, offline use, device support, a Compose summarizer, cloud fallback and limits.
Build a secure AI chat in your Android app with Firebase AI Logic and Gemini: setup, App Check, model choice, streaming ViewModel, Compose UI and error handling.
Diagnose a faded Material 3 card, pair its foreground and background colors, and check the result in both light and dark mode.