pub fn mutableStateOf<T: Clone + PartialEq + 'static>(
initial: T,
) -> MutableState<T>Expand description
Creates a new MutableState initialized with the given value.
MutableState is a cheap copyable observable handle. Reads are tracked by the
current composer or snapshot, and writes trigger recomposition of scopes that
read it.
Writing a value equal to the one already there is not a change, so it does
not recompose anything – Jetpack Compose’s structuralEqualityPolicy(),
which is its default too. Use mutableStateOfNeverEqual for a value that
cannot be compared, or one whose every write must count.
§When to use
Use mutableStateOf when:
- You are creating state properties inside a struct or class (not a composable function).
- You are implementing a custom state management solution.
Inside a #[composable] function this must sit inside a remember,
either rememberMutableStateOf for a single state or remember around
the struct that holds several. Called straight from a composable body it
makes a new state every pass and loses the value, exactly as in Kotlin.
§Example
struct MyViewModel {
name: MutableState<String>,
}
impl MyViewModel {
fn new() -> Self {
Self {
name: mutableStateOf(String::from("Alice")),
}
}
}
#[composable]
fn rememberMyViewModel() -> MyViewModel {
remember(MyViewModel::new).with(|model| model.clone())
}A state made while a remember is building its value belongs to that
slot and is released with it, which is what lets the struct above be
remembered whole. Made anywhere else it is owned by the runtime and lives
as long as the runtime does; to tie that to a Rust owner instead, store an
OwnedMutableState or call MutableState::retain on the handle.