How to display a loading icon on every request in the API? On the first request it shows the progress icon but on the second request it's like it cached and didn't show the load.
My viewModel:
class CadastroViewModel:ViewModel() {
private val cadastroRepository= CadastroRepository()
private val _resultado: MutableStateFlow<MessageCad> = MutableStateFlow(MessageCad())
val resultado: StateFlow<MessageCad>
get() = _resultado
fun create(nome: String,email: String,cpf:String,telefone:String,
celular:String,senha:String,endereco:String,bairro:String,numero:String,
complemento:String,cidade:String
){
viewModelScope.launch {
try {
val r = cadastroRepository.createUser(nome,email,cpf,telefone,celular,senha,endereco,bairro,
numero,complemento,cidade)
_resultado.value = r
} catch (e:Exception) {
Log.d("Service error",e.toString())
}
}
}
}
My view model call :
val value: MessageCad by model.resultado.collectAsState(initial = MessageCad())
if(value.message.isEmpty()){
CircularProgressIndicator(modifier = Modifier.wrapContentWidth(Alignment.CenterHorizontally))
}
The problem looks like value.message.isEmpty()
never returning true after first call because model.resultado
always have a result that is not empty.
You should either create a loading flag
private val _loading = MutableStateFlow(Boolean)
val loading: StateFlow<Boolean>
get() = _loading
set it as
viewModelScope.launch {
try {
_loading.value = true
val r = cadastroRepository.createUser(nome,email,cpf,telefone,celular,senha,endereco,bairro,
numero,complemento,cidade)
_resultado.value = r
}catch (e:Exception){
Log.d("Service error",e.toString())
}finally {
_loading.value = false
}
}
or use ViewState
approach to have Loading
, Success or Error states to display for any possible state of your api call.