Jetpack compose: View Model and mutablestatelistof
Video: Jetpack compose: View Model and mutablestatelistof by Taught by Celeste AI - AI Coding Coach
Watch full page →Jetpack Compose: Using ViewModel with MutableStateListOf
In Jetpack Compose, managing UI state efficiently is crucial for building responsive and maintainable apps. This example demonstrates how to use a ViewModel combined with mutableStateListOf to hold and update a list of items that automatically triggers UI recomposition when changed.
Code
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
// ViewModel holding a mutable state list of strings
class MyViewModel : ViewModel() {
// Initialize the list with some items
private val _items = mutableStateListOf("Apple", "Banana", "Cherry")
val items: List<String> get() = _items
// Function to add a new item to the list
fun addItem(item: String) {
_items.add(item)
}
// Function to remove an item from the list
fun removeItem(item: String) {
_items.remove(item)
}
}
// Usage in a Composable function (simplified)
/*
@Composable
fun ItemListScreen(viewModel: MyViewModel = viewModel()) {
val items = viewModel.items
Column {
items.forEach { item ->
Text(text = item)
}
Button(onClick = { viewModel.addItem("New Fruit") }) {
Text("Add Item")
}
}
}
*/
Key Points
mutableStateListOfcreates a mutable list that Jetpack Compose observes for changes, triggering recomposition.- Encapsulating the state list inside a ViewModel separates UI logic from data management and survives configuration changes.
- Exposing the list as an immutable
Listhelps maintain unidirectional data flow and prevents external modification. - Adding or removing items via ViewModel functions updates the list and automatically refreshes the UI.
- Using Compose with ViewModel and
mutableStateListOfcreates a clean and reactive architecture for list-based UI components.