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
flosch
08/04/2021, 3:36 PM
Use the
StateFlow.collectAsState
extension in your composable
Copy code
@Preview
@Composable
fun LoadingSpinner() {
val loading = viewModel.loadingState.collectAsState()
if (loading) {
CircularProgressIndicator()
}
}