ryanw-mobile / giphy-trending

Material 3, MVVM Kotlin Coroutine, Compose, REST API, Ktor, Room, DaggerHilt
Other
17 stars 4 forks source link

Apply Kotlin Flow debounce to the search input field #239

Open ryanw-mobile opened 1 month ago

ryanw-mobile commented 1 month ago

This can be a good application we use Kotlin Flow so the search keyword submission can be automated (and we don't need the search button)

ryanw-mobile commented 1 month ago

This is an example how we could implement this using Flow (which simulates RxJava/XML)

class SearchViewModel : ViewModel() {
    private val _query = MutableStateFlow("")

    init {
        viewModelScope.launch {
            _query
                .debounce(300) // Debounce the input by 300ms
                .distinctUntilChanged() // Only process if the value has changed
                .collectLatest { searchQuery ->
                    performSearch(searchQuery) // Perform the search operation
                }
        }
    }

    fun onSearchQueryChanged(query: String) {
        _query.value = query // Update the query in StateFlow
    }

    private fun performSearch(query: String) {
        // Perform the search (e.g., network/API call)
    }
}