Kotlin Android debounce

前端 未结 10 855
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 11:07

Is there any fancy way to implement debounce logic with Kotlin Android?

I\'m not using Rx in project.

There is a way in Java, but it is too big

10条回答
  •  星月不相逢
    2020-12-05 11:29

    For a simple approach from inside a ViewModel, you can just launch a job within the viewModelScope, keep track of the job, and cancel it if a new value arises before the job is complete:

    private var searchJob: Job? = null
    
    fun searchDebounced(searchText: String) {
        searchJob?.cancel()
        searchJob = viewModelScope.launch {
            delay(500)
            search(searchText)
        }
    }
    

提交回复
热议问题