kotlin (Jetpack组合)->加载状态未正确工作

tcbh2hod  于 2023-02-05  发布在  Kotlin
关注(0)|答案(1)|浏览(139)

我试图显示一个加载微调器,但加载状态总是在组合函数上显示一个false值。
我创建了一个自定义微调器,但它不显示

@Composable
private fun MainContent(viewModel: SearchJourneyViewModel = hiltViewModel()) {
    val state = viewModel.state
    
    Loader(isDialogVisible = state.isLoading)
}

在viewModel中,加载状态正在刷新并返回我需要的值:

@HiltViewModel
class SearchJourneyViewModel @Inject constructor(
    private val cityRepository: CityListRepository,
) : ViewModel() {

    var state by mutableStateOf(SearchJourneyState().mock())
        private set

    init {
        loadCityList()
    }

 private fun loadCityList() {
        viewModelScope.launch {
            cityRepository
                .getCityList()
                .collect { result ->
                    when (result) {
                        is Resource.Success -> {
                            state = 
                                state.copy(
                                    fromCity = //result,
                                    toCity = //result,
                                    isLoading = false,
                                    error = null
                                )
                            } 
                        }

                        is Resource.Error -> {
                            state = 
                                state.copy(
                                    fromCity = null,
                                    toCity = null,
                                    isLoading = false,
                                    error = result.message
                            )
                        }

                        is Resource.Loading -> {
                            state =
                                state.copy(isLoading = result.isLoading)
                        }
                    }
                }
        }
    }
}

以下是我的状态:

data class SearchJourneyState(
    val cityList: List<City>? = null,
    val isLoading: Boolean = false,
    val isCityLoading: Boolean = false,
)
kgsdhlau

kgsdhlau1#

主要的问题似乎是你收集状态的方式。
尝试将其定义为StateFlow

val viewStateFlow: StateFlow<VS> = MutableStateFlow()

然后只需将其收集到UI层:

val viewState by viewModel.viewStateFlow.collectAsState()

然后您应该能够在UI中加载更改:)

相关问题