https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sudhir Singh Khanger

07/22/2021, 12:45 PM
Copy code
val 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.
s

stojan

07/22/2021, 12:50 PM
I guess it's missing the canceling of the previous
Job
... it also becomes much easier if you transform the text changes to:
Flow<String>
... the logic then becomes:
Copy code
myTextChanges.debounce(300)
        .mapLatest { doSomeSuspendOp() }
and you don't have to deal with
Job
s

Sudhir Singh Khanger

07/22/2021, 1:32 PM
Supposedly using launch { } solves all the problems. There is no Job. It seems like the blog post is a copy paste job. https://pro100svitlo.medium.com/edittext-debounce-with-kotlin-coroutines-fd134d54f4e9
s

stojan

07/22/2021, 1:45 PM
check the first response to the post 👆 it's also pointing out the issue of not canceling previous jobs
3 Views