I tried to show a loading spinner, but loading state is always showing a false value on a compose function.
I've created a custom spinner, but it not shows
@Composable
private fun MainContent(viewModel: SearchJourneyViewModel = hiltViewModel()) {
val state = viewModel.state
Loader(isDialogVisible = state.isLoading)
}
In viewModel loading state is refreshing and returning a value that I need:
@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)
}
}
}
}
}
}
And here is my state:
data class SearchJourneyState(
val cityList: List<City>? = null,
val isLoading: Boolean = false,
val isCityLoading: Boolean = false,
)
The main issue seems to be the way you are collecting your state.
Try define it as a StateFlow
:
val viewStateFlow: StateFlow<VS> = MutableStateFlow()
And then simply collect it your UI layer:
val viewState by viewModel.viewStateFlow.collectAsState()
Then you should be able loading changes in UI:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.