当你不想做一些繁重的计算/操作时需要记住,而当你的组合被重组时,有时你的操作可能会改变,所以你需要进行计算或更新记住的值才能使用过时的初始计算值。
fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
mutableStateOf(newValue)
}.apply { value = newValue }
rememberUpdatedState 功能与使用remember 和mutableState 在value 发生变化时触发重组 相同。
@Composable
private fun Calculation(input: Int) {
val rememberUpdatedStateInput by rememberUpdatedState(input)
val rememberedInput = remember { input }
Text("updatedInput: $rememberUpdatedStateInput, rememberedInput: $rememberedInput")
}
var myInput by remember {
mutableStateOf(0)
}
OutlinedButton(
onClick = {
myInput++
}
) {
Text("Increase $myInput")
}
Calculation(input = myInput)
这是一个非常基本的示例,展示了 values 从 remember 和 rememberUpdatedState 的变化
更实际的例子是 lambdas
例如,假设您的应用有一个 LandingScreen,它会在一段时间后消失。即使LandingScreen被重构,等待一段时间并通知时间过去的效果也不应该重新启动:
@Composable
fun LandingScreen(onTimeout: () -> Unit) {
// This will always refer to the latest onTimeout function that
// LandingScreen was recomposed with
val currentOnTimeout by rememberUpdatedState(onTimeout)
// Create an effect that matches the lifecycle of LandingScreen.
// If LandingScreen recomposes, the delay shouldn't start again.
LaunchedEffect(true) {
delay(SplashWaitTimeMillis)
currentOnTimeout()
}
/* Landing screen content */
}
在此示例中,LaunchedEffect 被调用一次,但此 LandingScreen 函数可以重新组合,并且可能需要您更改 onTimeOut,因此使用 rememberUpdatedState 可确保在延迟后调用最新的 onTimeout。