You can try to assign your seachText to text variable when it is initialized with value from database. The idea is to assign value to text variable when the view is recomposed. You will need another variable searchTextLoaded for this.
In your viewModel class remove runBlocking and add function saveSearchTextToPreferences:
fun getSearchTextFromPreferences() = userPreferencesRepository.searchText
fun saveSearchTextToPreferences(text: String) {
viewModelScope.launch {
userPreferencesRepository.saveSearchText(text)
}
}
In your composable:
val searchText = viewModel.getSearchTextFromPreferences().collectAsState("").value
var text by remember { mutableStateOf("") }
var searchTextLoaded by remember { mutableStateOf(false) }
if (searchText.isNotEmpty() && !searchTextLoaded) {
text = searchText
searchTextLoaded = true
}
TextField(
value = text,
onValueChange = { newText ->
text = newText
viewModel.saveSearchTextToPreferences(newText)
},
label = { Text("Search") }
)
Here is link to complete app code on github: https://github.com/alba221/flightsearch