Ryan Simon
04/12/2022, 3:40 AM@Composable
fun FavoriteButton(
onClick: (Boolean) -> Unit,
isFavorited: Boolean,
modifier: Modifier = Modifier
) {
val fill = remember { mutableStateOf(isFavorited) }
IconButton(onClick = {
fill.value = !fill.value
onClick.invoke(isFavorited)
}, modifier = modifier) {
Icon(
imageVector = if (fill.value) Icons.Default.Favorite else Icons.Outlined.FavoriteBorder,
contentDescription = stringResource(
id = if (fill.value) R.string.remove_favorite_button else R.string.favorite_button
),
tint = Theme.colors.onBackground,
)
}
}
@Composable
fun FavoriteButton(
onClick: (Boolean) -> Unit,
isFavorited: Boolean,
modifier: Modifier = Modifier
) {
val fill = remember { mutableStateOf(isFavorited) }
if (fill.value) {
FavoritedButton(onClick = { onClick(fill.value) }, modifier = modifier)
} else {
NotFavoritedButton(onClick = { onClick(fill.value) }, modifier = modifier)
}
}
@Composable
fun FavoritedButton(onClick: () -> Unit, modifier: Modifier = Modifier) {
IconButton(onClick = onClick, modifier = modifier) {
Icon(
imageVector = Icons.Default.Favorite,
contentDescription = stringResource(id = R.string.remove_favorite_button),
tint = SizzleTheme.colors.onBackground,
)
}
}
@Composable
fun NotFavoritedButton(onClick: () -> Unit, modifier: Modifier = Modifier) {
IconButton(onClick = onClick, modifier = modifier) {
Icon(
imageVector = Icons.Outlined.FavoriteBorder,
contentDescription = stringResource(id = R.string.favorite_button),
tint = SizzleTheme.colors.onBackground,
)
}
}
nschulzke
04/12/2022, 4:24 AMisFavorited
to true and then switch it back to false, which is rather clunky and somewhat defeats the purpose (avoiding altering the ViewModel until it's actually worked).
If instead you just update the ViewModel state right away but have the ViewModel roll the state back if the network request fails, it would work fine right out of the box.
In general, I have a strong preference for using a single source of truth where possible. I've seen far too many UIs that duplicate their state in one way or another, and it always comes back to bite you later by getting out of sync in hard-to-debug ways.Ryan Simon
04/12/2022, 4:55 AMPaul Woitaschek
04/12/2022, 5:17 AMZach Klippenstein (he/him) [MOD]
04/14/2022, 4:04 PMRyan Simon
04/14/2022, 4:59 PMZach Klippenstein (he/him) [MOD]
04/14/2022, 5:55 PMRyan Simon
04/14/2022, 5:59 PM