0

I know this question has been asked many times over but I can't get any of the solutions to work.

I am implementing a TextWatcher and I want to make a network request but only when the user has finished typing. Here is my code.

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) {}
    }

How do I wait to find out if the user is not typing anymore before performing searchPlaces(s).

Gilbert
  • 2,699
  • 28
  • 29
  • 4
    This is referred to as **debouncing**, and you can find an example here for instance: https://stackoverflow.com/questions/50858684/kotlin-android-debounce and https://stackoverflow.com/questions/12142021/how-can-i-do-something-0-5-second-after-text-changed-in-my-edittext – user2340612 May 28 '20 at 19:16
  • "I know this question has been asked many times over but I can't get any of the solutions to work" Which have you tried and why didn't they work? – fweigl May 28 '20 at 20:39

1 Answers1

0

I have been able to solve the problem by setting up a Timer in the ViewModel thanks to user2340612's comment.

 // 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)
    }
Gilbert
  • 2,699
  • 28
  • 29