I have a view model injected with hilt that controls the state of a loading spinner, which is a fullscreen dialog.
@HiltViewModel
class MyViewModel @Inject constructor(
val coordinator: MyCoordinator
) : ViewModel() {
private val _isChanging = MutableStateFlow(false)
val isChanging = _isChanging.asStateFlow()
fun change() {
_isChanging.value = true
// suspend function which takes about 5 seconds to resolve
coordinator.change()
_isChanging.value = false
}
}
MyCoordinator
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
fun change() {
applicationScope.launch {
// do something for 5 seconds
delay(5000)
}
}
And finally the ui
@Composable
fun MyScreen(
viewModel: MyViewModel = hiltViewModel()
) {
val changing by viewModel.isChanging.collectAsStateWithLifecycle()
if (changing) {
AnimatedLoadingSpinner()
}
// other ui, including a button that triggers viewModel::change in the onClick lambda
}
When I press the button, the ui does indeed change. But the loading spinner never shows. How can I get the loading spinner to display?