-
Notifications
You must be signed in to change notification settings - Fork 100
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Currently there is no (lint) warning when using derivedStateOf without accessing any State object in its calculation, which can lead to unexpected behaviour. Since no State object is read, the derived value will never update which however might not be obvious just by looking at the code.
Let's take the following Composable for example:
@Composable
fun Amount(
amount: Int,
modifier: Modifier = Modifier,
) {
val isZeroAmount by remember { derivedStateOf { amount == 0 } }
Box(modifier = modifier) {
if (isZeroAmount) {
Text("Amount: Is zero")
} else {
Text("Amount: $amount")
}
}
}If amount is 1 initially and becomes 0 on the next recomposition, the Composable will incorrectly display Amount: 0 instead of Amount: Is zero.
This might for instance happen when a State variable with by delegation is changed to a plain type.
The correct code for this case would be:
@Composable
fun Amount(
amount: State<Int>,
modifier: Modifier = Modifier,
) {
val isZeroAmount by remember { derivedStateOf { amount.value == 0 } }
Box(modifier = modifier) {
if (isZeroAmount) {
Text("Amount: Is zero")
} else {
Text("Amount: ${amount.value}")
}
}
}Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request