I have a screen where I wan't to show a loading circle until I readed the default text values for two variables stored in datastore. I'm getting these values in a coroutine in the init block of the viewmodel of the screen. And I update loading to false after the collect of these two flows.
The problem is that for reading these values from the flows returned by datastore, I'm using collect, and collect doesn't end, so the loading circle is never disabled. The idea is to put to false the loading if no variables are on the flows or if one variable is returned by each flow. How to solve this situation?
init {
viewModelScope.launch(Dispatchers.IO) {
dataStoreRepository.readString("KEY").collect { value ->
updateKey(value)
}
dataStoreRepository.readString("NAME").collect { value ->
updateName(value)
}
_uiState.update { currentState ->
currentState.copy(loading = false)
}
}
}
I have a screen where I wan't to show a loading circle until I readed the default text values for two variables stored in datastore. I'm getting these values in a coroutine in the init block of the viewmodel of the screen. And I update loading to false after the collect of these two flows.
The problem is that for reading these values from the flows returned by datastore, I'm using collect, and collect doesn't end, so the loading circle is never disabled. The idea is to put to false the loading if no variables are on the flows or if one variable is returned by each flow. How to solve this situation?
init {
viewModelScope.launch(Dispatchers.IO) {
dataStoreRepository.readString("KEY").collect { value ->
updateKey(value)
}
dataStoreRepository.readString("NAME").collect { value ->
updateName(value)
}
_uiState.update { currentState ->
currentState.copy(loading = false)
}
}
}
Share
Improve this question
asked Mar 12 at 12:05
NullPointerExceptionNullPointerException
37.8k80 gold badges231 silver badges405 bronze badges
3
|
1 Answer
Reset to default 0I would use the combine extension function for this. The below example should hopefully demonstrate how it could be done. Replace keyStringFlow & nameStringFlow
with your datastore flows
val keyStringFlow = MutableStateFlow("")
val nameStringFlow = MutableStateFlow("")
val booleanFlow: Flow<Boolean> = keyStringFlowbine(nameStringFlow) { key, name ->
return@combine key.isNotEmpty() && name.isNotEmpty()
}
init {
viewModelScope.launch {
booleanFlow.collect { boolean ->
}
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744753800a4591757.html
updateKey
andupdateName
do. You generally don't want to collect flows in the view model, so whatever you do here should be done some other way. Please also provide_uiState
and how it is updated elsewhere. – tyg Commented Mar 12 at 17:25