To query after 2 seconds after user stop typing, I think you can use debounce operator (similar idea to the answer here Jetpack Compose and Room DB: Performance overhead of auto-saving user input?)
Here is an example to handle text change on TextField
, then query to database and return the result to dbText
class VM : ViewModel() {
val text = MutableStateFlow("")
val dbText = text.debounce(2000)
.distinctUntilChanged()
.flatMapLatest {
queryFromDb(it)
}
private fun queryFromDb(query: String): Flow<String> {
Log.i("TAG", "query from db: " + query)
if (query.isEmpty()) {
return flowOf("Empty Result")
}
// TODO, do query from DB and return result
}
}
In Composable
Column {
val text by viewModel.text.collectAsState()
val dbText by viewModel.dbText.collectAsState("Empty Result")
TextField(value = text, onValueChange = { viewModel.text.value = it })
Text(text = dbText)
}