Is it possible to perform some action after input on TextField?

1.9k views Asked by At

I use TextField as a search box. When the user types in some text, the app performs a search in the DB. I hope not to have an extra "search" button, the app should just search as the user types, but hopefully not on every single stroke, better only when the user pauses typing. How can I do it?

1

There are 1 answers

0
nglauber On

I'm assuming that you're using Kotlin Flow, but you can do almost the same thing if you use RxJava. Basically, what you need is the debounce operator in your flow.

You can achieve the desired result doing the following:

class YourSearchViewModel : ViewModel() {
    // These flows represents the term which the user is searching for
    private val _textSearch = MutableStateFlow("")
    val textSearch: StateFlow<String> = _textSearch.asStateFlow()

    init {
        viewModelScope.launch {
            // As soon the textSearch flow changes, 
            // if the user stops typing for 1000ms, the item will be emitted
            textSearch.debounce(1000).collect { query ->
                // Call the search function here using the query param
            }
        }
    }

    // This function will make the textSearch value changes
    fun setSearchText(it: String) {
        _textSearch.value = it
    }
    ...
}

Finally, in your composable, you can do:

val textSearch by viewModel.textSearch.collectAsState()
TextField(value = textSearch, onValueChange = viewModel::setSearchText)