如何在 api 中的每个请求上显示加载图标

How to display a loading icon on every request in the api

如何在 API 中的每个请求上显示加载图标?在第一个请求中它显示进度图标,但在第二个请求中它就像被缓存了并且没有显示负载。

我的视图模型:

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())
            }
        }
    }
}

我的视图模型调用:

val value: MessageCad by model.resultado.collectAsState(initial = MessageCad())
    
if(value.message.isEmpty()){
    CircularProgressIndicator(modifier = Modifier.wrapContentWidth(Alignment.CenterHorizontally))
}

问题看起来像 value.message.isEmpty() 在第一次调用后从未返回 true 因为 model.resultado 总是有一个不为空的结果。

您应该创建一个加载标志

private val _loading = MutableStateFlow(Boolean)
val loading: StateFlow<Boolean>
        get() = _loading

设为

  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
            }

        }

或使用 ViewState 方法使 Loading、成功或错误状态显示为您的 api 调用的任何可能状态。