Hi all, I have this issue with StateFlow: MainAct...
# compose
m
Hi all, I have this issue with StateFlow: MainActivity:
Copy code
...
    val loading = binding.loading
    loading.setContent {
        LoadingSpinner()
    }
...

@Preview
@Composable
fun LoadingSpinner() {
    if (viewModel.loadingState.value) {
        CircularProgressIndicator()
    }
}
in my viewmodel:
Copy code
_loadingState.value = true
viewModelScope.launch {
    doSomeLongTask()
    _loadingState.value = false //or calling this at some later point
}
LoadingSpinner() is updated correctly when value == true, but then when I set it to false, LoadingSpinner does not get updated and so stays on screen. Any help appreciated!
f
Use the
StateFlow.collectAsState
extension in your composable
Copy code
@Preview
@Composable
fun LoadingSpinner() {
    val loading = viewModel.loadingState.collectAsState()
    if (loading) {
        CircularProgressIndicator()
    }
}
z
Would be nice to have a warning about this, filed: https://issuetracker.google.com/issues/195445764
👍 3
m
Yes it worked! Thank you @flosch. Only difference was I needed to do
Copy code
if (loading.value) {
instead 🙂
f
Ah sorry, yea I forgot it is a delegate, you can also instead write
val loading by viewModel.loadingState.collectAsState()
Then you do not need the
.value
m
awesome thanks!