Pablo
02/18/2025, 7:26 PMfun readInt(key: String): Flow<Int> {
return context.dataStore.data.map { preferences -> preferences[intPreferencesKey(key)] ?: 0}
}
And Having this UiState and this ViewModel:
data class UiState(val value: Int = 0)
class ScreenViewModel(): ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState())
val uiState: StateFlow<nUiState> = _uiState
init {
viewModelScope.launch(Dispatchers.IO) {
val value = CustomDataStoreUtil.readInt("KEY")
_uiState.value = _uiState.value.copy(value = value)
}
}
How can I solve this situation? the datastore readInt
returns a Flow<Int>
but I need to save just the Int inside my UiState as you can see in my viewmodelSeri
02/18/2025, 7:28 PMreadInt()
once and use it for your viewmodel's initial state, or do you want the viewmodel's state to react to new values from your preference store?Pablo
02/18/2025, 7:29 PMCustomDataStoreUtil.readInt("KEY").collect { value -> // Once the value is emitted from the flow, update the UiState _uiState.value = UiState(value = value) }
or to do this?
CustomDataStoreUtil.readInt("KEY").first()
Pablo
02/18/2025, 7:29 PMSeri
02/18/2025, 7:32 PMMutableStateFlow.update(...)
for better atomic/threadsafe behavior.
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-mutable-state-flow/#1996476265%2FFu[…]ns%2F1975948010Pablo
02/18/2025, 7:35 PMinit {
viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
CustomDataStoreUtil.readInt("KEY").collect { value ->
_uiState.update { currentState ->
currentState.copy(value = value)
}
}
}
}
Pablo
02/18/2025, 7:35 PMPablo
02/18/2025, 7:35 PMSeri
02/18/2025, 7:52 PMcollect
here will inherit the lifetime of your viewModelScope
. Since viewModelScope
is a lifetime-aware component, it will respect your viewmodel's lifespanPablo
02/18/2025, 8:52 PM