【问题标题】:How to make network request only after the user stops typing如何仅在用户停止键入后才发出网络请求
【发布时间】:2020-09-16 05:28:32
【问题描述】:

我知道这个问题已经被问过很多次了,但我无法得到任何解决方案。

我正在实现TextWatcher,并且我想发出网络请求,但前提是用户完成输入。 这是我的代码。

val StartFragment.textWatcher: TextWatcher
    get() = object : TextWatcher {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            searchPlaces(s)
        }

        override fun afterTextChanged(s: Editable?) {}
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    }

在执行searchPlaces(s) 之前,我如何等待确定用户是否不再输入。

【问题讨论】:

标签: kotlin


【解决方案1】:

感谢user2340612的评论,我已经能够通过在ViewModel中设置Timer来解决问题。

 // In the ViewModel
 private var timer = Timer()
 private val delay: Long = 500L

 fun searchPlaces(placeName: String) {
        searchWord.value = placeName
        timer.cancel()
        timer = Timer()
        timer.schedule(object: TimerTask() {
            override fun run() {
                viewModelScope.launch {
                    repository.searchPlaces(placeName)
                }
            }
        }, delay)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2018-08-07
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多