Ramitsuri007
12/16/2024, 12:57 PMRamitsuri007
12/16/2024, 12:58 PM@Composable
fun ScreenContent(
vm: MyViewModel,
toggleTheme: () -> Unit,
) {
val viewState by vm.dataAvailable.collectAsStateWithLifecycle()
var dataAvailable by remember { mutableStateOf(false) }
val text = if (dataAvailable) {
"Data available"
} else {
"Data not available"
}
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
when (viewState) {
MyViewModel.ViewState.Data -> {
dataAvailable = true
Text(text, color = MaterialTheme.colorScheme.onBackground)
Button(onClick = toggleTheme) {
Text("Change theme")
}
}
MyViewModel.ViewState.Loading -> {
CircularProgressIndicator()
}
}
}
}
Ramitsuri007
12/16/2024, 12:58 PMclass MyViewModel : ViewModel() {
private val _dataAvailable: MutableStateFlow<ViewState> = MutableStateFlow(ViewState.Loading)
val dataAvailable: StateFlow<ViewState> = _dataAvailable
init {
viewModelScope.launch {
delay(1000)
_dataAvailable.value = ViewState.Data
}
}
sealed class ViewState {
data object Loading : ViewState()
data object Data : ViewState()
}
}
gmz
12/16/2024, 1:56 PMdataAvailable
from within a SideEffect
. I know SideEffect
fixes it, but I'm curious to know if that's the right thing to do here.
I personally would have simply made text
depend on viewState
rather than using this sort of indirection, but that's not relevant to your question.gmz
12/16/2024, 2:04 PMviewState
to a constant value
val viewState = MyViewModel.ViewState.Data
Stylianos Gakis
12/16/2024, 2:43 PMdataAvailable
exist in the first place? Do you want it to survive config changes? If yes, you want rememberSaveable.
Also, never do such backwards writes in composition like that, always look into using the side effect apis when you want to do... a side effect in composition like assigning a value.
The docs have a dedicated section on this https://developer.android.com/develop/ui/compose/performance/bestpractices#avoid-backwardsgmz
12/16/2024, 3:16 PMdataAvailable
), but that doesn't happen, while the doc you linked says otherwise.
As I mentioned in my messages I understand why the snippet could cause problems, but I've always seen State objects as something special that didn't need this kind of special treatment. But I agree that this is not the best way to write a compostable, as I also mentioned in my previous messages.Ramitsuri007
12/16/2024, 6:54 PMStylianos Gakis
12/16/2024, 7:00 PMAndreas Kindblom
12/17/2024, 9:08 AMvar dataAvailable by rememberSaveable { mutableStateOf(false) }
EDIT!
I would also have thought that your code should have worked though 🤷Ramitsuri007
12/17/2024, 10:56 AMStylianos Gakis
12/17/2024, 11:31 AMRamitsuri007
12/17/2024, 11:35 AM