MutableState
- Kotlin course
- Expert
- Lesson 34/47
- 5 min
Learn reactive state with mutableStateOf.
What is MutableState?
mutableStateOf is the reactive state creator of Compose. When the value changes, bound composables redraw automatically.
Example: val state = mutableStateOf(0). You read and write state.value. Writing makes Compose redraw every composable that observes this state. No manual subscription is needed; Compose tracks it automatically. Used with remember { mutableStateOf(0) }, the state is both retained and reactive. The stateInfo model in this lesson shows the concept.
Reading and writing state
You access a MutableState value through .value. Reading makes the composable an observer; writing triggers a redraw.
Example: val s = remember { mutableStateOf(0) }, then Text("${'$'}{s.value}"). Writing s.value = 5 makes Compose redraw the Text. This is unidirectional data flow: state flows down, events flow up. Compose manages this flow automatically; no manual update.
Practice Write stateInfo
Define fun stateInfo(): String. It should return "MutableState". In main, write println(stateInfo()).
Starter code
// add the stateInfo function
fun main() {
// print the state info
}Sample solution
fun stateInfo(): String = "MutableState"
fun main() {
println(stateInfo())
}Expected output
MutableState
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which creates reactive state?
The reactive state creator is mutableStateOf.- val x = 0
- var y = 0
- const z = 0
- val s = mutableStateOf(0) Correct answer
Explanation: mutableStateOf produces reactive state.
2 Complete the mutableStateOf call
val state = ____
val state = mutableStateOf(0)
Explanation: mutableStateOf(0) creates reactive state.
3 Match the MutableState parts
| Term | Meaning |
|---|---|
mutableStateOf |
State creator |
state.value |
Value access |
recomposition |
Auto redraw |
remember |
Retention |