I have a method that reads an int from datastore (...
# android
p
I have a method that reads an int from datastore (which returns FlowInt):
Copy code
fun readInt(key: String): Flow<Int> {
    return context.dataStore.data.map { preferences -> preferences[intPreferencesKey(key)] ?: 0}
}
And Having this UiState and this ViewModel:
Copy code
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 viewmodel
s
Do you want to read the value from
readInt()
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?
p
I want to react to new values, Is it the best option to do this?
Copy code
CustomDataStoreUtil.readInt("KEY").collect { value -> // Once the value is emitted from the flow, update the UiState _uiState.value = UiState(value = value) }
or to do this?
Copy code
CustomDataStoreUtil.readInt("KEY").first()
or another option?
s
Your first approach should work well! As well, consider using
MutableStateFlow.update(...)
for better atomic/threadsafe behavior. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-mutable-state-flow/#1996476265%2FFu[…]ns%2F1975948010
p
you mean doing this?
Copy code
init {
    viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        CustomDataStoreUtil.readInt("KEY").collect { value ->
            _uiState.update { currentState ->
                currentState.copy(value = value)
            }
        }
    }
}
is that the correct way to use update?
👍 1
and also, how long will be alive the collect method?
s
The
collect
here will inherit the lifetime of your
viewModelScope
. Since
viewModelScope
is a lifetime-aware component, it will respect your viewmodel's lifespan
p
thank you Seri