Sudhir Singh Khanger
07/22/2021, 12:45 PMval watcher = object :TextWatcher{
private var searchFor = ""
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val searchText = s.toString().trim()
if (searchText == searchFor)
return
searchFor = searchText
launch {
delay(300) //debounce timeOut
if (searchText != searchFor)
return@launch
// do our magic here
}
}
override fun afterTextChanged(s: Editable?) = Unit
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
}
I came across this piece of code as a sample of debouncing. But it seems to me that it basically launches a new coroutine every time onTextChanged
is called and then it executes the code after 300 seconds. That sounds like even a worse idea.stojan
07/22/2021, 12:50 PMJob
...
it also becomes much easier if you transform the text changes to: Flow<String>
...
the logic then becomes:
myTextChanges.debounce(300)
.mapLatest { doSomeSuspendOp() }
and you don't have to deal with Job
Sudhir Singh Khanger
07/22/2021, 1:32 PMstojan
07/22/2021, 1:45 PM