remember gives a composable function memory. A value computed by remember will be stored in the composition tree, and only be recomputed if the keys to remember change. You can think of remember as giving storage for a single object to a function the same way a private val property does in an object.
mutableStateOf creates a MutableState<T> which is an observable state holder built into compose. interface MutableState<T> : State<T> { override var value: T } Any changes to value will automatically recompose any composable functions that read this state. You declare a MutableState object in a composable three ways: *val state = remember { mutableStateOf(default) } *var value by remember { mutableStateOf(default) } *val (value, setValue) = remember { mutableStateOf(default) } When creating State<T> (or other stateful objects) in composition, it's important to remember it. Otherwise it will be re-initialized every composition. MutableState<T> similar to MutableLiveData<T>, but integrated with the compose runtime. Since it's observable, it will tell compose whenever it's updated so compose can recompose any composables that read it.
上面是英文解释,下面看一个例子:
Column() { var name = remember{ ""} Text(text = name) TextField(value = name, onValueChange = {name= it}) } Column() { val name = remember{ mutableStateOf("")} Text(text = name.value) TextField(value = name.value, onValueChange = {name.value = it}) }
第一个代码,text并不会随textfield改变而改变,因为name虽然被“记住”在内存中,但是它是一个“死”的值,没有生命,次次都使用里面的值,系统并不知道有新的值。但mutablestate是一种observable对象,当值改变,会通知系统recompose,如果它不remember,recompose时会被重新初始化,故需要和remember配套使用才有效果。