Having a composable wich haves a textfield
which needs to work with a by remember mutablestateof String
called text
, that variable must be initialized with a datastore
stored value. I have the datastore
repo on the viewmodel
, but it returns a Flow
, which also needs to be executed in a coroutine. So… I’m stuck.
I can’t return directly the Flow
and do collectAsStateWithLifecycle
because it needs a coroutine, and I can’t return the coroutine because it returns a job and I need a string. How to solve this?
This is my datastore variable with the initial value for the field, and this is in my viewmodel:
userPreferencesRepository.searchText
This is the datastore value code, in my datastore repo class:
val searchText: Flow<String> = dataStore.data
.catch {
if (it is IOException) {
Log.e(TAG, "Error reading preferences.", it)
emit(emptyPreferences())
} else {
throw it
}
}
.map { preferences ->
preferences[SEARCH_TEXT] ?: ""
}
A sample of a textfield that should receive that text variable from viewmodel, but I don’t know how to get it.
viewModel: FlightsScreenViewModel = viewModel(factory = FlightsScreenViewModel.factory)
TextField(
value = text,
onValueChange = { newText ->
text = newText
},
label = { Text("Search") }
)